Osc*_*son 6 javascript prototype prototypal-inheritance prototype-programming
我正在尝试从父级继承属性,但我不清楚正确的方法.
让我们说:
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;
}
Run Code Online (Sandbox Code Playgroud)
现在我想添加一个子原型继承,所以我不必手动添加父项中的所有内容.例如,假设我想添加一个Cat基于Animal
我想这样做,就像它是一个 Animal
var pet = new Cat('Kitty');
pet.createOffspring();
Run Code Online (Sandbox Code Playgroud)
无需手动添加name和createOffspringCat constructor,这实际上只是一个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
Run Code Online (Sandbox Code Playgroud)
而已?(UPD:修复了原型错误)(UPD2:对不起。已是深夜,我犯了很多错误。我必须去睡觉)
还有另一种解决方案,但特定于Chrome,FF(可能是其他解决方案):
// Animal and Cat functions from above, but
Cat.prototype = {
__proto__: Animal.prototype,
constructor: Cat,
meow: function() { ... }
}
Run Code Online (Sandbox Code Playgroud)
看起来更短,但不被这个吸引:最好遵循ECMAScript标准。
| 归档时间: |
|
| 查看次数: |
3875 次 |
| 最近记录: |