谁能给我解释一下为什么A
是真的,而B
是假的?我本以为B也是真的。
function MyObject() {
};
MyObject.prototype.test = function () {
console.log("A", this instanceof MyObject);
(function () {
console.log("B", this instanceof MyObject);
}());
}
new MyObject().test();
更新:从ecmascript-6开始,您可以使用箭头函数,这样可以很容易地引用MyObject:
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();
发布于 2011-12-30 01:09:20
在匿名函数中,this
绑定到全局对象(浏览器环境中的window
)。
访问实例的方式有多种:
var self = this;
(function () {
console.log("B", self instanceof MyObject);
}());
或
(function () {
console.log("B", this instanceof MyObject);
}).call(this);
发布于 2011-12-30 01:09:11
this
根据您调用函数的方式进行设置。
您的匿名函数是一个普通的函数调用,所以this
是全局对象。
您可以编写(function() { ... }).call(this)
以使用this
显式调用它。
https://stackoverflow.com/questions/8670877
复制相似问题