继承函数如何在Node.js中工作?

时间:2012-02-25 03:18:15

标签: javascript inheritance node.js

这是node.js中的继承函数:

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable:    false,
      writable: true,
      configurable: true
    }
  });
};

有人可以给我一个关于这个功能如何运作的“大图”吗? 我不是100%肯定我得到了Object.create,而且......我很困惑!

非常感谢任何帮助/指示...

Merc的。

2 个答案:

答案 0 :(得分:3)

var Parent = function () {
  this.isParent = true;
};

Parent.prototype.doSomething = function () {
  return 42;
};

var Child = function () {
  this.isChild = true;
}
util.inherits(Child, Parent);

var c = new Child;
console.log(c.isChild);
console.log(c.doSomething());

它只是确保Child.prototype正确地从Parent.prototype继承。它还将constructor属性Child.prototype设置为正确的值。

确保在util.inherits声明后直接致电Child

答案 1 :(得分:-1)

现在有两个版本的继承功能。 Pre node.js 5.0.0版使用Object.create,post(包含)v5.0.0使用Object.setPrototypeOf。

在Object.create版本中,superCtor的原型被设置为ctor.prototype的原型。但是,在此过程中,将删除ctor.prototype上可用的任何方法/属性。这是一个有效的例子;



var inherits = function (ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
};

function Manager(managerName) {
    this.managerName = managerName;
}

Manager.prototype.getManagerName = function () {
    return this.managerName;
}

function Team(managerName, teamName) {
    this.teamName = teamName;
    Team.super_.apply(this, arguments);
}


Team.prototype.getTeamDetails = function () {
    return this.teamName + ' is managed by ' + this.managerName;
}

inherits(Team, Manager);

var obj = new Team('Klopp', 'LiverpoolFC');

console.log(obj.getTeamDetails()); //obj.getTeamDetails is not a function




上述问题在Node.js 5.0.0或更高版本中得到解决。 util.inherits现在使用setPrototypeOf来解决这个问题。



var inherits = function (ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
        constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
};

function Manager(managerName) {
    this.managerName = managerName;
}

Manager.prototype.getManagerName = function () {
    return this.managerName;
}

function Team(managerName, teamName) {
    this.teamName = teamName;
    Team.super_.apply(this, arguments);
}


Team.prototype.getTeamDetails = function () {
    return this.teamName + ' is managed by ' + this.managerName;
}

inherits(Team, Manager);

var obj = new Team('Klopp', 'LiverpoolFC');

console.log(obj.getTeamDetails()); //obj.getTeamDetails is not a function




此链接提供了继承如何在Node.js中工作的详细说明 Node.js - Anatomy of inherits