1

当我使用var关键字声明任何变量时,它会在封闭范围内声明。但是在下面的代码中,我已经用关键字声明了函数c(在对象方法内部),并且函数内部仍然绑定到全局对象。为什么是这样?a.bvarthiscwindow

var a = {
        b: function () {
            var c = function () {
                return this;
            };
            return c();
        }
    };

document.write(a.b());  //prints: [object Window]
4

2 回答 2

3

的值this取决于上下文,而不是范围。

当您调用一个没有任何上下文 ( context.func()) 的函数时 ( c()) 时,默认上下文是默认对象(window在浏览器中),除非您处于严格模式(在这种情况下它是undefined相反的)。

(此规则有例外,例如applycallbindnew但它们都不适用于此)。

于 2013-06-16T12:45:33.307 回答
1

Many people get confused by . The value depends on one of 4 methods of invocation.
However, functional invocation and cause most of the confusion.
If a function is a member of an object, is the object itself.

obj.someFunction(); //method invocation

If a function is called without context is the global object (in 'strict mode' is undefined.)

someFunction();  //functional invocation

The confusion occurs when a function is called within an object, but not as a member of the object as in anObject.testWithHelper(..);

var testForThis = function(isThis, message) {
    //this can be confusing
    if(this === isThis) 
        console.log("this is " + message);
    else
        console.log("this is NOT " + message);    
};  

//functional invocation
testForThis(this, "global"); //this is global

var anObject = {
    test: testForThis, //I am a method
    testWithHelper: function(isThis, message) {
        //functional invocation
        testForThis(isThis, message + " from helper");
    }
};

//method invocation
anObject.test(anObject, "anObject"); //this is anObject
//method invocation followed by functional invocation
anObject.testWithHelper(anObject, "an object"); //this is NOT anObject from helper

Here is my JSFIDDLE

If you would like c to return a, you can use :

var a = {
    b: function () {
        var that = this;
        var c = function () {
            return that;
        };
        return c();
    }
};

Or avoid this all together:

var getNewA = function() {
    var newA = {};
    newA.b = function() {
        var c = function() {
            return newA;
        };
        return c();
    };    
    return newA;
};

var newA = getNewA();
于 2013-07-02T12:12:44.037 回答