javascript - 从成员函数访问函数成员变量

标签 javascript closures this

Foo 是一个具有名为 list 的公共(public)成员的函数。它有一个名为 setList 的公共(public)成员函数。我希望能够从 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,所以如果我用了错误的名称,请原谅我。

最佳答案

假设您使用 Foo 创建实例:

function Foo()
{
    this.list = ["a", "b", "c"];

    this.setList = function(data) {
        this.list = data;
    }
}

var x = new Foo();
console.log(x.list); // a,b,c
x.setList([]);
console.log(x.list); // empty array

关于javascript - 从成员函数访问函数成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309766/

相关文章:

javascript - 如何列出 props 变量中的项目?

dart - 函数中的 'Closure'是什么?

Javascript::在闭包中生成新变量并通过对象实例使用它

javascript - 无法使用 .bind 更改分配给该对象的值

c++ - 在类中使用相同的变量可以在构造函数 C++ 中使用吗?

javascript - 在 reactjs Material ui 进度条中显示百分比数

javascript - 谷歌表格: How do I get my custom function to refresh automatically?

javascript - 将事件监听器添加到自定义指令中的 ui-select

javascript - 意外的关闭行为

javascript - 对象函数属性中的 React 类 : Referencing class as "this",