-1

In the following code, why test function's second this points to obj, whereas the first this points to window object?

In particular, how can I guess the value of this by looking at a piece of code?

var test = function(){
    console.log('first', this)
    return function(){
        console.log('second', this)
    }
}

var obj = {
    a: 1,
    b: test()
}

obj.b() // execute function
Maria
  • 3,055
  • 6
  • 29
  • 41
  • no need to guess - with `test()` called as a bare function - `this === window`, but with the function returned by `test` called as a property of `obj` - `this === obj`. – Alnitak Nov 05 '19 at 17:41
  • When you execute `test()` it's in the global context and you're running in non-strict mode, hence `window` is assigned to `this`. When you call the inner function through `obj.b()` the `obj` is assigned to `this`. The value of `this` is determined at call time: as a simple rule of thumb `this` will have the value of whatever is the *last thing* before the dot when you execute, so with `obj.b` -> `obj`. if you have `obj1.obj2.obj3.prop()` -> `obj1.obj2.obj3`. If there is no dot, and you just call `test()`, then it's the global object or `undefined` (depending on strict/non-strict mode). – VLAZ Nov 05 '19 at 17:43

1 Answers1

0

You call test on object creation triggering the first logging and store the created function to the object. You call that function on global level and therefore this gets resolved at that scope.

Is this some sort of interview question? What are you trying to achieve/understand?

Edit: See this guide for a good explanation of 'this': https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/

Stefan Vitz
  • 116
  • 8