4

我正在使用 node.js 和基于 express.js 的编程。我曾尝试用util.inheritsJavaScript 来实现继承。我尝试过的如下:

//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);
});

我的情况是:

我有Request作为基类和Create子类。请求具有在构造函数target中初始化的字段。oldRequest

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

我为此搜索了类似的线程,但都是我尝试过的!任何人都可以解释出了什么问题吗?

提前致谢 :)

4

1 回答 1

6

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

 Create.super_.prototype.process.call(this, callback);

但真的,

 var super_ = Request.prototype;

然后语法变得几乎很方便:

 super_.process.call(this, callback);
于 2013-08-05T16:24:27.143 回答