S
S
Stepan2014-08-07 22:19:40
JavaScript
Stepan, 2014-08-07 22:19:40

Why doesn't an array work in a constructor?

function Hamster() {
    this.food = []
}
Hamster.prototype = {
    found: function(something) {
        this.food.push(something)
    }
}

speedy = new Hamster()
lazy = new Hamster()

speedy.found("apple")
speedy.found("orange")

console.log(speedy.food.length) // 2
console.log(lazy.food.length) // 0 (!??)

I read javascript.ru there is this example. Like, each hamster should have 1 in the array. But when calling, we get that one has 0 in the array and the other has 2. Explain how it works?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Petrov, 2014-08-07
@xoma2

So you put 2 fruits on the speedy hamster and nothing on the lazy hamster. Lazy is nervous...
Why don't you use var?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question