Reputation: 1576
Foo is a function with a public member called list. It has a public member function called setList. I want to be able to edit list from setList. Can I do that? I've attempted a few things, but I haven't been able even to access list from inside 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.
Upvotes: 1
Views: 110
Reputation: 495
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/
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.
Upvotes: 0
Reputation: 173562
Assuming you're creating instances with 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
Upvotes: 1