如何从Javascript中的构造函数继承构造函数?

Joh*_*ohn 8 javascript inheritance constructor

所以我正在学习Javascript及其所有'原型优点,我对以下内容感到难过:

说我有这个

var Animal = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

var x = new Animal(1,2,3....);
Run Code Online (Sandbox Code Playgroud)

现在我如何创建一个继承自Animal构造函数的Cat构造函数,这样我就不必再次输入超长参数了?

换句话说,我不想这样做:

var Cat = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

// inherit functions if any
Cat.prototype = new Animal;

var y = new Cat(1,2,3....);
Run Code Online (Sandbox Code Playgroud)

提前致谢!Ĵ

SLa*_*aks 9

这个怎么样?

var Cat = Function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   Animal.apply(this, arguments);
};

// inherit functions if any
Cat.prototype = new Animal;

var y = new Cat(1,2,3....);
Run Code Online (Sandbox Code Playgroud)

  • Yu甚至不需要在Cat函数中声明参数列表(a,b,c等).参数仍将包含新Cat(1,2,3 ...)调用中发送的值. (4认同)
  • 小心:`prototype = new Animal`调用实例化一个`Animal`,调用构造函数,所有参数都设置为`undefined`.对于一个只存储其参数的简单构造函数,这是可以接受的,但对于任何更复杂的构造函数,它都会破坏.背景和(冗长!)讨论:http://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript/1598077 (3认同)