문제

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
도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top