Javascript:如何正确扩展类

peh*_*has 8 javascript prototype

通过互联网搜索我总是碰到这种Javascript类扩展的方法

function extend(Child, Parent) {
    var F = function() { }
    F.prototype = Parent.prototype
    Child.prototype = new F()
    Child.prototype.constructor = Child
    Child.superclass = Parent.prototype
}
Run Code Online (Sandbox Code Playgroud)

但是这与那个有什么不同呢?

  function extend(Child, Parent) {
    var p = new Parent()
    Child.prototype = p
    Child.prototype.constructor = Child
    Child.superclass = p
  }
Run Code Online (Sandbox Code Playgroud)

最后一个也很完美.那我为什么要用这个额外的var F = function() { }动作呢?

coo*_*ter 7

直接调用原始构造函数可能会产生不良副作用,如果未传递某些预期参数,则无法正常工作.

这就是为什么他们使用"代理"功能,它允许你获得一个继承Parent()而不实际调用的新对象Parent().


这是一个简单的例子:

function Person(name, age) {
    if (name === undefined)
        throw "A name is required";
    this.name = name + "";
    this.age = age;
}
Run Code Online (Sandbox Code Playgroud)

如果Person是父级,则会抛出错误,因为没有name传递.

  • 嗯......有人不喜欢这个答案吗?我犯了错误吗? (2认同)