【发布时间】:2019-01-08 08:25:26
【问题描述】:
我无法确定是什么概念解释了为什么对象的属性“count”的值保留在下面的代码中。
我已阅读并查看了 Getify 的 You Don't Know JS 中的 this 和对象原型部分 以及他们解释lexical this的部分。 但是,我无法理解下面的代码。 是词法作用域吗? 还是 this 绑定允许保留 count 的值?
下面是示例代码:
var obj = {
count: 0,
method: function() {
console.log("in method: " + this.count)
return this.count++;
},
}
// here is where I have issue, when the method is invoked as a function
for (var i = 0; i<10; i++) {
console.log(obj.method()) // invoked as a function
}
// I've left this small block in for convenience
// I have no trouble with understanding why this block outputs what it outputs
for (var i = 0; i<10; i++) {
console.log(obj.method) // "gets its value (a reference to a function) and then logs that" from TJ Crowder
}
我希望对 obj.method() 的第一个方法调用的输出能够输出
// 0
// in method 0
// 1
// in method 1
// 2
.
.
.
// 10
// in method 10
我对输出的内容没有任何问题。我的问题又是,是词法作用域吗? 还是 this 绑定允许保留 count 的值?
感谢您抽出宝贵时间提供帮助。
编辑 1 在下面 Tj Crowder 的帖子的帮助下,我编辑了代码 sn-p 以清除错误,因为它偏离了我的问题。
【问题讨论】:
-
也许有助于区分不同的日志调用?然后你可以看到哪个打印哪个输出
-
你没有从
method()函数返回任何东西,所以它打印undefined。想做return this.count;? -
我已经编辑了 sn-p 来表达我的问题的初衷。我最初提供的代码在根本问题和您的回复方面具有误导性,我深表歉意并感谢您的回复。
标签: javascript this lexical-scope