4
我正在使用node.js和基于express.js的编程。我试图用util.inherits
来实现JavaScript中的继承。我已经试过如下:Node.JS中的继承
//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
,它在Request
构造函数中初始化old
。
现在,我创建了Create
类对象,它首先调用Request
构造函数,然后使用new
初始化target
字段。当我打电话给Create
的处理函数时,我期望得到target is 'new'
的消息,但它返回另一个!
我搜索了类似的线程为此,但都是我试过!任何人都可以解释什么是错的?
感谢提前:)
哦,非常感谢! –