Question

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
Was it helpful?

Solution

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';
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top