【问题标题】:Access function member variable from member function从成员函数访问函数成员变量
【发布时间】: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


【解决方案1】:

假设您使用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

【讨论】:

    【解决方案2】:

    您还可以设置一个原型,它会产生相同的结果。我可以解释为什么有时您可能想要使用原型的原因,但是此链接提供了有关该主题的良好信息http://thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/

    function Foo(){
      this.list = [1,2,3];
    }
    
    Foo.prototype = {
      setList: function(data){
        this.list = data;
      }
    };
    
    var x = new Foo();
    x.setList(['hello', 'hi']);
    console.log(x.list);
    

    这将记录传递给 x.setList 的数组,它是 ['hello', 'hi'] 显示该列表已更新。

    【讨论】: