Pregunta

I'm in the process of learning Javascript prototypes and trying to understand why this is happening. It's my understanding that when looking for the value of a property, the object is checked before any prototype. When then, does this print "brown"?

function Box(item) {
    this.item = item;
}

Box.prototype.color = "brown";
Box.color = "blue";

var box = new Box(null);
console.log(box.color);

>>> brown
¿Fue útil?

Solución

Box.color = "blue"; assigns a property to the function Box, not to an instance of it. You can easily verify that by running console.dir(box) and console.dir(Box).

If you want to assign the property to an instance, you have to create the instance first:

Box.prototype.color = "brown";

var box = new Box(null);
box.color = "blue"

or assign it inside the constructor function:

function Box(item) {
    this.item = item;
    this.color = 'blue';
}

Otros consejos

Because Box.color is the constructor's property, it will never assigned to a instance object. After you initialize the box object, it only gets this.item and prototype.color property.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top