0

假设我有一个构造函数:

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()`
4

3 回答 3

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!
于 2012-10-19T22:07:52.140 回答
0

好的,更容易使用apply

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

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

  return Construct
}
于 2012-10-19T21:53:03.717 回答
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
于 2012-10-19T22:13:52.273 回答