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
347 views
in Technique[技术] by (71.8m points)

ecmascript 6 - this value in JavaScript anonymous function

Can anybody explain to me why A is true and B is false? I would have expected B to be true as well.

function MyObject() {

};

MyObject.prototype.test = function () {
    console.log("A", this instanceof MyObject);
    (function () {
        console.log("B", this instanceof MyObject);
    }());
}

new MyObject().test();

update: since ecmascript-6 you can use arrow functions which would make it easy to refer to MyObject like this:

function MyObject() {

};

MyObject.prototype.test = function () {
    console.log("A", this instanceof MyObject);
    (() => {//a change is here, which will have the effect of the next line resulting in true
        console.log("B", this instanceof MyObject);
    })(); //and here is a change
}

new MyObject().test();    
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Inside of your anonymous function this is the global object.

Inside of test, this is the instance of MyObject on which the method was invoked.


Whenever you call a function like this:

somceFunction(); // called function invocation

this is always the global object, or undefined in strict mode (unless someFunction was created with bind** — see below)

Whenever you call a function like this

foo.someMethod();  //called method invocation

this is set to foo


**EcmaScript5 defines a bind function that allows you to create a function that has a pre-set value for this

So this

    var obj = { a: 12 };
    var someFunction = (function () { alert(this.a); }).bind(obj);
    someFunction();

Causes someFucntion to be invoked with this equal to obj, and alerts 12. I bring this up only to note that this is a potential exception to the rule I mentioned about functions invoked as

someFunction();

always having this equal to the global object (or undefined in strict mode)


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

...