谁能向我解释为什么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();