0

I know that this variable refers to either the global object (window in case of browsers) or the object that contains it (in case is used in an object's method), unless it is differently specified (e.g using the bind method).

Now, I have the following example:

//define an object
var obj = {
    param: 'Luciano',
    bar: function () {
        console.log('"this" inside method: ' + this);
        return this;
    }
};

var a = obj.bar();
console.log(a);
//
var b = obj.bar;
console.log(b());

​ the output is:

"this" inside method: [object Object]

Object {param: "Luciano"}

"this" inside method: [object Window]

Window { ... }

I can understand why in case of var a = obj.bar() the this variable points to the obj object. Could someone explain to me please (in terms of execution contexts and scope chain) why in case of var b = obj.bar the this variable equals to window object ? I would expect to be equal to obj too.

ira
  • 5,569
  • 6
  • 30
  • 41
  • 2
    That's how JavaScript works if you execute the function without context the context will be window object or undefined if run in strict mode. – jcubic May 23 '16 at 13:09
  • 1
    Voting to reopen. This is not a duplicate. While it does address similar problem it actually asks why `.` didn't bind context to `bar` function when not used with `()`. The simple answer is "because that's how it is" but it does require at least some explanation. – freakish May 23 '16 at 13:22
  • I would highly recommend looking at this: https://www.youtube.com/watch?v=nRZri_CHqnA to understand javascript scope. – Stacker-flow May 24 '16 at 10:15

1 Answers1

0

What you actually did with var b = obj.bar; b(); is "take method bar of obj and call it directly, without this (or with window as this)" vs obj.bar() which means "call method bar with obj as this".

The confusion comes from the fact that . is not just simple "give me a value for a key", it also "binds" a context if used together with () symbols afterwards. Otherwise it does not.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • thank you for your answer. I haven't realize that in the second case I was actually executing the function without context. – ira May 23 '16 at 17:11