execution context and (( this object ))

// 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


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;
    }
};
链接地址: http://www.djcxy.com/p/94918.html

上一篇: 对象字面声明中的引用

下一篇: 执行上下文和((this object))