【发布时间】:2018-06-14 16:56:34
【问题描述】:
问题 - 如何获得从父(动物)继承到子(兔子)原型的正确方法,在创建对象后不会覆盖父原型道具,基于子原型。我的意思是,创建对象(兔子)必须从兔子原型获取原型方法(.prototype.walk),而不是从父(动物)获取。
我知道我们可以轻松解决并将 this.walk 方法移到构造函数 Animal 后面并创建原型方法 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"
【问题讨论】:
-
“我们不能使用这个技巧” - 为什么不呢?你应该这样做。
-
@Bergi 是的,我知道,但还有其他方法吗?问题是有几次我遇到了具有这种继承性的父原型,实际上我们不允许从构造函数中获取方法,将它们制作成原型。
-
"实际上我们不允许从构造函数中获取方法" - 我认为你需要解决这个问题,而不是寻找比显而易见的更好的解决方法.
标签: javascript inheritance constructor prototype