构造函数继承自Constructor

时间:2013-04-20 19:37:15

标签: javascript

好吧,假设我有一个像这样的构造函数:

var Base = function() {};
Base.prototype.shmoo = function() { this.foo="shmoo"; }

如何创建其他独立于Base的构造函数,并且彼此分开?

换句话说,派生构造函数的扩展功能仅影响其对象而不影响Base,而不影响另一个派生构造函数。

我试过

Extender = function() {};
Extender.prototype = Base.prototype;
Extender.prototype.moo = function() { this.moo="boo"; };

但当然,这在任何地方都会生效。

我应该模拟类层次结构吗?我试图远离那种模式。

1 个答案:

答案 0 :(得分:1)

这将实现原型继承(这是你想要的):

 // The Extender prototype is an instance of Base but not Base's prototype     
Extender.prototype = new Base();

// Set Extender() as the actual constructor of an Extender instance
Extender.prototype.constructor = Extender; 
相关问题