this value in JavaScript anonymous function

前端 未结 4 1718
灰色年华
灰色年华 2020-11-28 11:58

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() {

};

MyOb         


        
4条回答
  •  清歌不尽
    2020-11-28 12:40

    In the anonymous function, this is bound to the global object (window in a browser environment).

    There are various ways of accessing the instance:

    var self = this;
    (function () {
        console.log("B", self instanceof MyObject);
    }());
    

    or

    (function () {
        console.log("B", this instanceof MyObject);
    }).call(this);
    

提交回复
热议问题