问题 - 如何获得从父(动物)继承到子(兔子)原型(prototype)的正确方法,这些方法不会在创建对象后基于子原型(prototype)覆盖父原型(prototype) Prop 。我的意思是,创建对象(兔子)必须从 Rabbit 原型(prototype)而不是父对象(Animal)获取原型(prototype)方法(.prototype.walk)。
我知道我们可以做一个简单的解决方案并将方法 this.walk 移到构造函数 Animal 后面并创建原型(prototype)方法 Animal.prototype.walk...但我想知道我们是否可以在不将 this.walk 推出构造函数的情况下做到这一点括号?这是一些 JS 技巧吗?
我将不胜感激,谢谢!
function Animal(name) {
this.name = name;
this.walk = function() {
console.log( "walk " + this.name );
};
}
// Animal.prototype.walk = function() { //// we can not use this trik and
// console.log( "walk " + this.name ); //// delete this.walk function in
//} //// constructor
function Rabbit(name) {
Animal.apply(this, arguments);
}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;
Rabbit.prototype.walk = function() {
console.log( "jump " + this.name );
};
var rabbit = new Rabbit("Rabbit");
rabbit.walk(); // for now we get "walk Rabbit". But need - "jump Rabbit"
最佳答案
如果 Animal
构造函数在每个实例上都定义了一个 .walk
函数,要覆盖它们,Rabbit
构造函数必须执行相同的操作:
function Rabbit(name) {
Animal.apply(this, arguments); // creates an own .walk property
// overwrites the own .walk property
this.walk = function() {
console.log( "jump " + this.name );
};
}
您还可以共享函数对象以更好地使用内存:
function rabbitWalkMethod() {
console.log( "jump " + this.name );
}
function Rabbit(name) {
Animal.apply(this, arguments);
this.walk = rabbitWalkMethod;
}
(您也可以使用 Rabbit.prototype.walk
属性来存储它而不是局部变量 rabbitWalkMethod
,但这可能会让任何读者感到困惑该方法正在继承)
关于javascript - 如何从父原型(prototype)JS继承权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104115/