如何调用父构造函数?

Moo*_*oon 25 javascript inheritance

假设我有以下代码段.

function test(id) { alert(id); }

testChild.prototype = new test();

function testChild(){}

var instance = new testChild('hi');
Run Code Online (Sandbox Code Playgroud)

有可能得到alert('hi')吗?我undefined现在明白了.

roy*_*rie 101

JS OOP ......

// parent class
var Test = function(id) {
    console.log(id);
};

// child class
var TestChild = function(id) {
    Test.call(this, id); // call parent constructor
};

// extend from parent class prototype
TestChild.prototype = Object.create(Test.prototype); // keeps the proto clean
TestChild.prototype.constructor = TestChild; // repair the inherited constructor

// end-use
var instance = new TestChild('foo');
Run Code Online (Sandbox Code Playgroud)

  • 道歉,"混乱"是苛刻的 - 它使_dirty_ proto链,将所有父实例属性指定为原型属性(可能不是你想要的),但是如果你不关心它,这项技术是有效的 - 例如:http: //imgur.com/NBDA5ob(干净继承会将'id'作为构造函数实例化的实例属性,而不是原型实体). (2认同)

Sk6*_*606 16

你已经有了很多答案,但我会抛出ES6的方式,恕我直言是这种方式的新标准方式.

class Parent { 
  constructor() { alert('hi'); } 
}
class Child extends Parent { 
  // Optionally include a constructor definition here. Leaving it 
  // out means the parent constructor is automatically invoked.
  constructor() {
    // imagine doing some custom stuff for this derived class
    super();  // explicitly call parent constructor.
  }
}

// Instantiate one:
var foo = new Child();  // alert: hi
Run Code Online (Sandbox Code Playgroud)

  • 好提醒 像往常一样,如果可能,最好将源代码转换为 ES5,以解决此问题和其他不兼容问题。您可以使用 Webpack、Typescript 等工具执行此操作。 (3认同)

Ant*_*off 7

这就是你在CoffeeScript中这样做的方法:

class Test
  constructor: (id) -> alert(id)

class TestChild extends Test

instance = new TestChild('hi')
Run Code Online (Sandbox Code Playgroud)

不,我没有开始圣战.相反,我建议看看生成的JavaScript代码,看看如何实现子类化:

// Function that does subclassing
var __extends = function(child, parent) {
  for (var key in parent) {
    if (Object.prototype.hasOwnProperty.call(parent, key)) {
      child[key] = parent[key];
    }
  }
  function ctor() { this.constructor = child; }
  ctor.prototype = parent.prototype;
  child.prototype = new ctor;
  child.__super__ = parent.prototype;
  return child;
};

// Our code
var Test, TestChild, instance;

Test = function(id) { alert(id); };

TestChild = function() {
  TestChild.__super__.constructor.apply(this, arguments);
}; __extends(TestChild, Test);

instance = new TestChild('hi');

// And we get an alert
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/NGLMW/3/上查看它的实际操作.

为了保持正确,与CoffeeScript输出相比,代码稍作修改并注释为更具可读性.