Danilo
Danilo

Reputation: 43

Reference and call object issue?

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?

Upvotes: 0

Views: 33

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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();

Upvotes: 3

Related Questions