请教下关于node继承的问题,为何使用了inherits还要在给构造方法里面使用父类的构造方法?看见很多开源代码都这么写
发布于 9 年前 作者 ZeeyanLeung 4618 次浏览 最后一次编辑是 8 年前 来自 问答

var Hybi = function(request, url, options) { Base.apply(this, arguments); }; util.inherits(Hybi, Base);

如题,直接inherits,为何还要调用父类的构造方法

4 回复
> console.log(util.inherits.toString())
function (ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
}

util.inherits将prototype加上了。这样才可以用父类的方法。

不掉用 父类的构造方法 只能继承原型链上的属性。没法仿问 函数内定义的内部属性。

var util = require('util');
var ConstructorA = function () {
    this.func1 = function () {
        console.log('im func1!!');
    }
};
ConstructorA.prototype.func2 = function () {
    console.log('im func2!!');
};

var ConstructorB = function () {
    //ConstructorA.call(this);
};

util.inherits(ConstructorB, ConstructorA);

var conb = new ConstructorB();
conb.func2();//正常。如果util.inherits(ConstructorB, ConstructorA);被注释了,这句将报错
conb.func1();//报错,上面ConstructorB里面注释的一行打开过后,这里就不报错了。

@20082496 正解,就是个prototype的问题,使用this调用父类构造函数相当于继承了属性,util没管这个滴~

回到顶部