Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Why does the value of "this" changes.?

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.

example 1:

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

var hello = myNamespace.myObject.sayHello;

hello(); // "name is undefined"

example 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"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...