简体   繁体   English

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

[英]Access function member variable from member function

Foo is a function with a public member called list. Foo是具有名为list的公共成员的函数。 It has a public member function called setList. 它具有一个名为setList的公共成员函数。 I want to be able to edit list from setList. 我希望能够从setList编辑列表。 Can I do that? 我可以那样做吗? I've attempted a few things, but I haven't been able even to access list from inside 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
    }
}

I'm still figuring JS out, so please forgive me if I've called something by the wrong name. 我仍在弄清JS,因此,如果我用错误的名字打电话给我,请原谅我。

Assuming you're creating instances with Foo : 假设您正在使用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

You could also set a prototype which will yield the same results. 您还可以设置一个将产生相同结果的原型。 I could explain reasons why sometimes you may want to use a prototype, but this link provides good information on that subject http://thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/ 我可以解释为什么有时您可能想要使用原型的原因,但是此链接提供了有关该主题的良好信息, 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);

this will log the array passed into x.setList which is ['hello', 'hi'] showing that list was update. 这将记录传递到x.setList的数组,该数组是['hello','hi'],表示列表已更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM