我正在尝试一种将动态原型模式与原型链相结合的继承模型。这项调查纯粹是学术性的,试图理解JavaScript中对象的属性。我相信可以推荐更好的模型。 我很好奇为什么这两种方法的组合无法生成我正在寻找的原型链。
function Animal(params) {
this.species = undefined;
this.sound = undefined;
if (params.species !== undefined){ this.species = params.species; }
if (params.sound !== undefined){ this.sound = params.sound; }
if (Animal.prototype.makeSound === undefined) {
Animal.prototype.makeSound = function() {
console.log(this.sound);
};
}
}
function Bear(params) {
if (params.species === undefined){ params.species = "Bear"; }
if (params.sound === undefined){ params.sound = "Grr"; }
Animal.call(this, params);
if (Bear.prototype.swipe === undefined) {
Bear.prototype = new Animal(params);
Bear.prototype.swipe = function() {
console.log("swipe - '" + this.sound + "'");
};
}
}
var bear = new Bear({});
bear.swipe(); // Uncaught TypeError: bear.swipe is not a function(…)
bear.makeSound(); // Uncaught TypeError: bear.makeSound is not a function(…)
如果我将原型定义移到构造函数之外(即不再是动态模式),这可以正常工作 - 删除链接调用中的参数&检查动物构造函数中的params使用:
function Animal(params) {
this.species = undefined;
this.sound = undefined;
if (params !== undefined) {
if (params.species !== undefined){ this.species = params.species; }
if (params.sound !== undefined){ this.sound = params.sound; }
}
}
Animal.prototype.makeSound = function() {
console.log(this.sound);
}
function Bear(params) {
if (params.species === undefined){ params.species = "Bear"; }
if (params.sound === undefined){ params.sound = "Grr"; }
Animal.call(this, params);
}
Bear.prototype = new Animal();
Bear.prototype.swipe = function() {
console.log("swipe - '" + this.sound + "'");
}
var bear = new Bear({});
bear.swipe(); // swipe - 'Grr'
bear.makeSound(); // Grr
我认为这是不打扰实际项目中的动态模式的原因。我只是好奇。
我想要做的完整示例是here