0

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!

Zout
  • 821
  • 10
  • 18
  • 2
    You're right about `this`. I'm confused about how you organized your code, but to get around the immediate problem, you could do `addNoise.call(this);` instead of just `addNoise();` which sets the value of `this` as you want in `addNoise` – Ian Aug 09 '14 at 17:26
  • Or just omit the function definition and call at all, they're local only anyway. – Bergi Aug 09 '14 at 18:26
  • 1
    I decided to close this as a duplicate since you mention *"In my actual code, the equivalent of addNoise runs asynchronously"* – Felix Kling Aug 09 '14 at 18:30

1 Answers1

-1

Best way to do this is to prototype the functions

functionon Car(make)
{
    this.make = make;
    this.noises = ["vroom", "woosh"];
    this.addNoise();
}

Car.prototype.addNoise = function() {
    this.noises.push("wham");
}

var myCar = new Car("honda");

console.log(myCar.noises[2]);
Blake A. Nichols
  • 870
  • 1
  • 6
  • 11