【发布时间】:2011-12-29 17:07:04
【问题描述】:
谁能向我解释为什么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();
【问题讨论】:
-
欢迎来到 JavaScript 中的函数作用域。
-
@zzzzBov:这不是闭包。
-
您可能希望使用额外的一对括号来提高可读性:
( new MyObject() ).test() -
@SLaks,我编辑了我的评论以正确反映匿名函数的用法,尽管它被用作闭包。
-
否;它没有被用作闭包。它没有结束任何事情。范围并不真正相关。
标签: javascript ecmascript-6 this anonymous-function