继承具有相同构造函数但不同/相似原型的类

时间:2012-10-19 21:41:33

标签: javascript

假设我有一个构造函数:

function Constructor(input) {
  this.input = input
}

Constructor.prototype.method = function() {
  console.log('a')
}

但我想使用构造函数的副本创建另一个类,但更改原型。

function Constructor2(input) {
  this.input = input
}

Constructor2.prototype.method = function() {
  console.log('b')
}

我不想重新定义构造函数。你会怎么做?理想情况下,这将是一件简单的事情:

var Constructor2 = inherits(Constructor)
Constructor2.prototype.method = // overwrite the inherited `method()`

3 个答案:

答案 0 :(得分:1)

var inherits = function(childCtor, parentCtor) {
  /** @constructor */
  function tempCtor() {};
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /** @override */
  childCtor.prototype.constructor = childCtor;
};



// How to use it:

var Constructor1 = function() {
//add all your methods, variables etc
};

Constructor1.prototype.myMethod = function() {
};

var Contructor2 = function() {
Contructor1.call(this); // Call the super class constructor
};
inherits(Contstructor2, Constructor1);
// Constructor2 now inherits from Constructor1
// override, add methods variables etc, whatever you need.

// Have fun!

答案 1 :(得分:0)

好的,只使用apply更容易:

function newConstructor(Super) {
  function Construct() {
    Super.apply(this, arguments)
  }

  require('util').inherits(Construct, Super)

  return Construct
}

答案 2 :(得分:0)

这是一个讨厌的解决方案:

function Constructor1(input) {
  this.input = input;
}

Constructor1.prototype.method = function() {
  console.log('a');
}

// be careful here: evals the string value of Constructor1 with references to "Constructor1" changed to "Constructor2"
eval(Constructor1.toString().replace("Constructor1", "Constructor2"));

Constructor2.prototype.method = function() {
  console.log('b');
}

var c1 = new Constructor1(1);
var c2 = new Constructor2(2);
console.log(c1.constructor === c2.constructor) // true

c1.method() // a
c2.method() // b