Javascript这个关键字 - 内部功能

时间:2014-04-07 11:10:42

标签: javascript this

我想了解 Javascript 上的this关键字。

我正在对Chrome控制台进行一些测试,我遇到了两个不同的结果,我期待它们是相同的:

var myTest = {};
myTest.test1 = function() {
        return this; // this = Object
}

第一个函数返回我理解的myTest对象。

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        return this; // this = Window
    }
}

为什么第二个函数返回窗口而不是myTest对象?

谢谢

1 个答案:

答案 0 :(得分:5)

this指的是调用该函数的当前对象。当你打电话给test1时,你就会这样做

myTest.test1()

现在,在test1对象上调用了myTest。这就是this在第一种情况下引用myTest的原因。

在第二种情况下,你会像这样执行

myTest.test1()()

myTest.test1()返回一个函数,并且您在没有任何当前对象的情况下进行调用。在这种情况下,JavaScript将确保this将引用全局对象(在这种情况下为window)。

注意:但是,在严格模式下,this将是undefined,在第二种情况下。您可以像这样确认

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

输出

this is global true
this is undefined false

但是如果你这样包含use strict

"use strict";

var myTest = {};
myTest.test1 = function() {
    return function test2() {
        console.log("this is global", this === window);
        console.log("this is undefined", this === undefined);
        return this;
    }
}

myTest.test1()();

输出

this is global false
this is undefined true
相关问题