0

I have a doubt about javascript references. So, if I have something like this:

a = function(){console.log('a')};
a['b'] = function(){console.log('b')}

Are these functions somehow related?

2
  • 3
    What this refers to depends on how the functions are called! In a['b']() this actually refers to a. Commented Mar 14, 2017 at 13:29
  • @Danilo: I've rolled back the changes. Questions on Stack Overflow are not meant to be moving targets. Once your question is asked and answered, fundamentally changing the question such that the answers no longer address the new question isn't how things are done here. If you have a follow-on question, post it separately. Commented Mar 14, 2017 at 14:41

1 Answer 1

3

You only have one variable there: a. But you've created a property on the function a refers to, called b, that refers to another function.

That's the only relationship the two functions have: One is referenced by a property on the other. Other than that, they're unrelated.

As Unicode-art:

      +−−−−−−−−−−−−−−−+
a−−−−>|  (function)   |
      +−−−−−−−−−−−−−−−+
      | ...stuff...   |
      | length: 0     |     +−−−−−−−−−−−−−−−+
      | b             |−−−−>|  (function)   |
      +−−−−−−−−−−−−−−−+     +−−−−−−−−−−−−−−−+
                            | ...stuff...   |
                            | length: 0     |
                            +−−−−−−−−−−−−−−−+

...with two different functions with this referring to window ?

As deceze pointed out, the value of this within calls to those functions will depend entirely on how they're called, as with most JavaScript functions. (The exceptions being bound functions, which have a value for this bound to them, and ES2015+ arrow functions, which close over the this where they're defined.)

In loose mode, doing a() will indeed call the first function with this referring to the global object (which is the window object on browsers). In strict mode, a() would call it with this set to undefined. You can also use a.call(anyValueHere) to call it with this set to any value (in strict mode; in loose mode, anyValueHere has to be an object or you get that global object again). If you assign a to an object property (var o = {a: a};) then call it via o.a(), this within the call with equal o. If you do new a, the first function will be called with this referring to the new object from new. Etc.

In fact, with what you have in your question, a.b() would call the second function with this referring to the first function!

var a = function(){console.log('a')};
a['b'] = function(){console.log("this is: ", this)}; // Note change
a.b();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.