【问题标题】:Inheritance nodejs继承nodejs
【发布时间】:2016-03-11 16:29:28
【问题描述】:

我正在尝试在 nodejs 中继承一个模块。当我只调用一次超级时,还可以,但是当我开始在其他代码点中调用它时,来自一个的数据在另一个......

RegEvent.js(超级)

var __ = require('lodash');
var RegEvent = function () {
    RegEvent.prototype.Model = new require('models/regValids')(this.model);
};

RegEvent.prototype.getAll = function () {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 0);
    var callback = args.pop();
    getAll(self, args[0], args[1] || {}, args[2] || {}, callback);
};
var getAll = function (scope, company, where, projection, callback) {
    scope.Model.get(company, where, projection, function (error, result) {
        return callback(error, result);
    });
};
module.exports = RegEvent;

configPerEmployee.js

var __ = require('lodash');
var inherits = require('util').inherits;
var RegEvent = require('components/regEvent');

var ConfigPerEmployee = function () {
    this.model = 'config_employees';
    RegEvent.apply(this, arguments);
};

inherits(ConfigPerEmployee, RegEvent);

ConfigPerEmployee.prototype.handlePriority = function (company, employee, callback) {
...
}

所以,我有另一个名为 schedules 的模块(如 configPerEmployee.js),它继承了 RegEvents,当我从 schedules 调用 getAll function 时,我从 configPerEmployee 访问模型。不知道怎么回事。

【问题讨论】:

  • 我猜使用 ES6 的节点会更容易获得这种行为,因为你可以创建类

标签: javascript node.js inheritance prototype


【解决方案1】:

我认为问题在于您每次创建 ConfigPerEmployee 等实例时都在重新分配 RegEvent.prototype.Model

为什么不把 RegEvent 构造函数改成

var RegEvent = function(modelName) {
  this.Model = new require('models/regValids')(modelName);
}

和 ConfigPerEmployee 等来

var ConfigPerEmployee = function() {
    RegEvent.apply(this, ['config_employees']);
};

【讨论】:

    猜你喜欢
    • 2016-04-30
    • 2017-06-30
    • 1970-01-01
    • 2015-04-19
    • 2012-10-30
    • 2017-12-27
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多