为什么“这个”的值是多少?变化。? [英] Why does the value of "this" changes.?

查看:145
本文介绍了为什么“这个”的值是多少?变化。?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning javascript and i came across a doubt. Why is the value of "this" undefined in the first example , but prints out correctly in the second.

示例1:

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

var hello = myNamespace.myObject.sayHello;

hello(); // "name is undefined"

示例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"

为什么this的值在函数内发生变化。我缺少什么概念?

Why does the value of "this" changes within the function. What concept am i missing?

推荐答案

第一种情况,你只是将函数的引用引入可修复的 hello ,并从全局上下文(浏览器中的窗口,节点中的全局)调用它,所以这个成为调用除(for)之外的函数功能)。您始终可以使用 function.call明确设置上下文或使用Ecma5将该上下文明确设置为该函数 function.bind

First case you are just getting the reference of the function to the vairable hello, and invoking it from global context (window in browsers, global in node), So this becomes what invoked the function except for (bound functions). You can always set the context explicitly using function.call or set the context explicitly to the function using Ecma5 function.bind

hello.call(myNamespace.myObject); //now you are setting the context explicitly during the function call.

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

or just bind it while getting the function reference.

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

第二如果您从对象本身调用它,那么指向该对象。

Second case you are invoking it from the object itself so this points to the object.

这篇关于为什么“这个”的值是多少?变化。?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆