问题描述
我一直在寻找关于 SO 的 Javascript 原型继承的好例子,这个问题 Benefits of using 'Object.create' for inheritance 有一个很好的答案,所以我试图通过向原型链添加另一个对象类型来推动我的运气,我发现了一些东西看起来很奇怪。
原始列表有 Dog
继承自 Animal
,我们可以在原型链中看到 Animal
。但是,如果我们添加 Creature
并让 Animal
继承自它,那么如果我们使用 console.info,Animal
就会从 reported 原型链中消失。
谁能解释一下为什么原型链不应该说 Dog
->Animal
->Creature
?
这是代码清单
"use strict";
//https://www.typescriptlang.org/docs/handbook/classes.html
var Creature = (function () {
function Creature() {
return this;
}
Creature.prototype.deadOrAlive = function () {
console.log("alive"); //hard code for Now
}
return Creature;
}());
var Animal = (function () {
Animal.prototype = Object.create(Creature.prototype);
function Animal() {
return this;
}
Animal.prototype.move = function (distanceInMeters) {
if (distanceInMeters === void 0) {
distanceInMeters = 0;
}
console.log("Animal moved " + distanceInMeters + "m.");
};
return Animal;
}());
var Dog = (function () {
/* https://stackoverflow.com/questions/17392857/benefits-of-using-object-create-for-inheritance/17393153#answer-17393153 */
Dog.prototype = Object.create(Animal.prototype);
function Dog() {
return this;
}
Dog.prototype.bark = function () {
console.log("Woof! Woof!");
};
return Dog;
}());
var dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
dog.deadOrAlive();
//debugger;
解决方法
我所在的 Javascript 新兵训练营的一位同事提出了一个单行解决方案,只需使用 Object.setPrototypeOf( Animal.prototype,Creature.prototype )
。谢谢,雷!
//https://www.typescriptlang.org/docs/handbook/classes.html
"use strict";
var Creature = (function () {
function Creature() {
return this;
}
Creature.prototype.deadOrAlive = function () {
console.log("alive"); //hard code for now
}
return Creature;
}());
var Animal = (function () {
Object.setPrototypeOf( Animal.prototype,Creature.prototype )
function Animal() {
return this;
}
Animal.prototype.move = function (distanceInMeters) {
if (distanceInMeters === void 0) {
distanceInMeters = 0;
}
console.log("Animal moved " + distanceInMeters + "m.");
};
return Animal;
}());
var Dog = (function () {
/* https://stackoverflow.com/questions/17392857/benefits-of-using-object-create-for-inheritance/17393153#answer-17393153 */
Object.setPrototypeOf( Dog.prototype,Animal.prototype )
function Dog() {
return this;
}
Dog.prototype.bark = function () {
console.log("Woof! Woof!");
};
return Dog;
}());
var dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
dog.deadOrAlive();
//debugger;