1

// I don't understand why this is not working

y = 'window';
var x = {
    y : 'x',
    func : function(){
        return function(){
            return this.y
        }
    }
};

x.func()();

// when I execute x.func()() I understand why it should return y
// x.func() would return a function in the global context and then execute it ' should return 'window' '
y = 'window'
var x = {
    y : 'x',
    func : function(){
        return function(){
            return this.y
        }()
    }
};

x.func();

why would this code also return 'window' it is executed inside of the x object

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34
  • possible duplicate of [Javascript "this" pointer within nested function](http://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function) –  Aug 31 '14 at 02:49

1 Answers1

1

The call x.func()() calls the function x.func using x as a context, then calls the value it returned using no context. Where the function was defined doesn’t matter; only how it was called does.

To avoid this, you can bind the function to a particular context before returning that:

var x = {
    y: 'x',
    func: function() {
        return function() {
            return this.y;
        }.bind(this);
    }
};

ES6 arrow functions also use a lexical this, equivalent to bind:

var x = {
    y: 'x',
    func: function() {
        return () => this.y;
    }
};
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • yes problem is with the second snippet ? this => gets evaluated at run time . it should return 'x' rather than 'window' right ? – Ahmed Eid Aug 31 '14 at 00:23
  • @user3260606: `(function () {})()` doesn’t execute with any context either, regardless of where it’s defined. `x.func()`, `x['func']()`, `func.call(x, …)`, and `func.apply(x, […])` are the only ways a function will be called with a non-default `this`. – Ry- Aug 31 '14 at 00:24