让我们说:
var Animal = function(name){
this.offspring = [];
this.name = name;
return this;
}
Animal.prototype.createOffspring = function(name){
name = name || 'Baby '+(this.offspring.length+1);
this.offspring.push(name);
return this;
}
现在我想添加一个子原型继承,所以我不必手动添加父项中的所有内容.例如,假设我想添加一个基于Animal的Cat
我想这样做,就好像它是动物一样
var pet = new Cat('Kitty');
pet.createOffspring();
无需手动将名称和createOffspring添加到Cat构造函数中,而Cat构造函数实际上只是一个Animal,但具有一些其他附加功能(如.meow()或其他东西).
最佳答案
// Parent
function Animal() {
this.name = 'An animal';
}
// Some child
function Cat() {
this.speaks = 'Meow';
}
// Here comes inheritence
Cat.prototype = new Animal();
// Or like that
// but don't forget to put all inheritable fields to Animal's prototype
Cat.prototype = Object.create(Animal.prototype);
// Let 'instanceof' work. Don't forget the following line,// because we eraese the info about constructor of Cat instances.
Cat.prototype.constructor = Cat;
// Add some custom method
Cat.prototype.meow = function() { return this.speaks; }
var cat = new Cat();
var animal = new Animal();
/// Some tests
cat.name; // A animal
animal.name; // An animal
cat.meow(); // Meow!
cat instanceof Cat; // true
cat instanceof Animal; // true
而已?
(UPD:修复原型时出错)
(UPD2:对不起.这是深夜,我犯了很多错误……我一定要睡觉了)
还有另一种解决方案,但其Chrome,特定于FF(可能还有其他):
// Animal and Cat functions from above,but
Cat.prototype = {
__proto__: Animal.prototype,constructor: Cat,meow: function() { ... }
}
看起来更短,但不会受此诱惑:最好遵循ECMAScript标准.