【发布时间】:2023-12-27 09:45:01
【问题描述】:
Foo 是一个具有名为 list 的公共成员的函数。它有一个名为 setList 的公共成员函数。我希望能够从 setList 编辑列表。我可以这样做吗?我尝试了一些事情,但我什至无法从 setList 中访问列表。
var Foo = function Foo() {
this.list = ["a", "b", "c"];
this.setList = function(data) {
// Attempt 1
console.log(list); // Uncaught ReferenceError: list is not defined
// Attempt 2
console.log(this.list); // undefined
// Attempt 3
console.log(Foo.list); // undefined
}
}
我还在摸索JS,所以如果我叫错了名字,请原谅我。
【问题讨论】:
-
你怎么称呼这段代码?另外,为什么要使用命名闭包作为构造函数?
-
this的值由函数调用方式决定。在不知道您如何称呼setList的情况下,我们不可能为您提供适当的帮助。假设你做的一切都是正确的,this.list应该可以工作。也许看看MDN - Introduction to Object-Oriented JavaScript。
标签: javascript closures this