为什么"this"的值会发生变化.

poo*_*ank 6 javascript this

我正在学习javascript,我遇到了一个疑问.为什么在第一个示例中未定义"this"的值,但在第二个示例中正确打印出来.

例1:

var myNamespace = {
    myObject: {
        sayHello: function() {
            console.log( "name is " + this.myName );
        },
        myName: "john"
    }
};

var hello = myNamespace.myObject.sayHello;

hello(); // "name is undefined"
Run Code Online (Sandbox Code Playgroud)

例2:

var myNamespace = {
    myObject: {
        sayHello: function() {
            console.log( "Hi! My name is " + this.myName );
        },
        myName: "Rebecca"
    }
};

var obj = myNamespace.myObject;

obj.sayHello();//"Hi! My name is Rebecca"
Run Code Online (Sandbox Code Playgroud)

为什么"this"的值在函数内发生变化.我错过了什么概念?

PSL*_*PSL 4

第一种情况,您只是获取函数对 vairable 的引用hello,并从全局上下文(浏览器中的窗口,节点中的全局)调用它,因此this成为除(绑定函数)之外调用该函数的内容。您始终可以使用 function.call显式设置上下文,或使用 Ecma5 function.bind显式设置函数上下文

hello.call(myNamespace.myObject); //now you are setting the context explicitly during the function call.
Run Code Online (Sandbox Code Playgroud)

或者只是在获取函数引用时绑定它。

var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject); //Now no matter where you call it from `this` will point to the context of myObject
Run Code Online (Sandbox Code Playgroud)

第二种情况是从对象本身调用它,因此this指向该对象。