Node.JS中的继承

Hos*_*her 4 inheritance node.js

我正在使用node.js和基于express.js的编程.我试图用util.inheritsJavaScript在JavaScript中实现继承.我试过的内容如下:

//request.js
function Request() {
    this.target = 'old';
    console.log('Request Target: ' + this.target);
}

Request.prototype.target = undefined;
Request.prototype.process = function(callback) {
    if (this.target === 'new')
       return true;

    return false;
}

module.exports = Request;

//create.js
function Create() {
    Create.super_.call(this);
    this.target = 'new';
}

util.inherits(Create, Request);

Create.prototype.process = function(callback) {
    if (Create.super_.prototype.process.call(this, callback)) {
        return callback({ message: "Target is 'new'" });
    } else {
        return callback({ message: "Target is not 'new'" });
    }
}

module.exports = Create;

//main.js
var create = new (require('./create'))();
create.process(function(msg) {
    console.log(msg);
});
Run Code Online (Sandbox Code Playgroud)

我的情况是:

我有Request基类和Create子类.Request具有在构造函数target中初始化的字段.oldRequest

现在,我创建了一个Create类对象,它首先调用Request构造函数,然后使用初始化target字段new.当我调用过程函数时Create,我希望得到消息,target is 'new'但它返回另一个!

我为此寻找了类似的线程,但所有这些都是我尝试过的!任何人都可以解释什么是错的吗?

提前致谢 :)

Esa*_*ija 6

util.inherits真的很尴尬super_......无论如何,这应该有效:

 Create.super_.prototype.process.call(this, callback);
Run Code Online (Sandbox Code Playgroud)

但是真的,

 var super_ = Request.prototype;
Run Code Online (Sandbox Code Playgroud)

然后语法变得几乎方便:

 super_.process.call(this, callback);
Run Code Online (Sandbox Code Playgroud)