Javascript 中的数据与继承冲突
Data conflict with inheritance in Javascript
我正在尝试处理 JavaScript 中的库,但我遇到了继承问题。这是我正在尝试做的一个简化示例:
Fruit = function () {
this.colors = [];
}
Lemon = function () {
this.colors.push("yellow");
}
Lemon.prototype = new Fruit();
在这里,我想创建一个 class Lemon,继承自 class Fruit,其中每个水果都包含一个颜色列表。
但是当我尝试实例化一些柠檬并像这样打印它们的颜色时:
var lemon1 = new Lemon();
console.log(lemon1.colors);
var lemon2 = new Lemon();
console.log(lemon1.colors);
console.log(lemon2.colors);
我得到这个输出:
["yellow"]
["yellow", "yellow"]
["yellow", "yellow"]
所以我可以看出问题是属性 "colors" 是 Lemon 对象的每个实例之间共享的一个数组。
如何为每个柠檬实例制作不同颜色的数组,并在 Fruit 中定义 class?
像这样:
Fruit = function () {
this.colors = [];
}
Lemon = function () {
Fruit.call(this);
this.colors.push("yellow");
}
Lemon.prototype = Object.create(Fruit);
从 Lemon
构造函数调用 Fruit
构造函数:Fruit.call(this);
。此外,我们不调用构造函数来创建原型,而是使用 Object.create(Fruit)
来创建对象而不调用其构造函数。
运行 您的示例使用上述定义给出了以下内容。
> var lemon1 = new Lemon();
> console.log(lemon1.colors);
[ 'yellow' ]
> var lemon2 = new Lemon();
> console.log(lemon1.colors);
[ 'yellow' ]
> console.log(lemon2.colors);
[ 'yellow' ]
对此我补充说:
> Object.is(lemon1.colors, lemon2.colors)
false
这表明 Lemon
个实例的 colors
属性.
的值具有不同的 Array
我正在尝试处理 JavaScript 中的库,但我遇到了继承问题。这是我正在尝试做的一个简化示例:
Fruit = function () {
this.colors = [];
}
Lemon = function () {
this.colors.push("yellow");
}
Lemon.prototype = new Fruit();
在这里,我想创建一个 class Lemon,继承自 class Fruit,其中每个水果都包含一个颜色列表。
但是当我尝试实例化一些柠檬并像这样打印它们的颜色时:
var lemon1 = new Lemon();
console.log(lemon1.colors);
var lemon2 = new Lemon();
console.log(lemon1.colors);
console.log(lemon2.colors);
我得到这个输出:
["yellow"]
["yellow", "yellow"]
["yellow", "yellow"]
所以我可以看出问题是属性 "colors" 是 Lemon 对象的每个实例之间共享的一个数组。
如何为每个柠檬实例制作不同颜色的数组,并在 Fruit 中定义 class?
像这样:
Fruit = function () {
this.colors = [];
}
Lemon = function () {
Fruit.call(this);
this.colors.push("yellow");
}
Lemon.prototype = Object.create(Fruit);
从 Lemon
构造函数调用 Fruit
构造函数:Fruit.call(this);
。此外,我们不调用构造函数来创建原型,而是使用 Object.create(Fruit)
来创建对象而不调用其构造函数。
运行 您的示例使用上述定义给出了以下内容。
> var lemon1 = new Lemon();
> console.log(lemon1.colors);
[ 'yellow' ]
> var lemon2 = new Lemon();
> console.log(lemon1.colors);
[ 'yellow' ]
> console.log(lemon2.colors);
[ 'yellow' ]
对此我补充说:
> Object.is(lemon1.colors, lemon2.colors)
false
这表明 Lemon
个实例的 colors
属性.
Array