This is basically what I'm trying to do (I'm new to Javascript, so bear with me):
function Car(make)
{
this.make = make;
var noises = ["vroom", "woosh"];
function addNoise()
{
noises.push("wham");
this.noises = noises;
}
addNoise();
}
var myCar = new Car("honda");
console.log(myCar.noises[2]);
Now, I think the issue is that when I do this.noises = noises;
, this
isn't referring to Car
, so when I try to do console.log(myCar.noises[2]);
noises is undefined. In my actual code, the equivalent of addNoise
runs asynchronously, so I have to be able to make noises
a property inside that function.
Edit:
Yes, that other question covers a similar problem. This seems to work:
function Car(make)
{
this.make = make;
var noises = ["vroom", "woosh"];
var self = this;
function addNoise()
{
noises.push("wham");
self.noises = noises;
}
addNoise();
}
var myCar = new Car("honda");
console.log(myCar.noises[2]);
Pretty simple solution!