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'
的消息,但它返回另一個!
我搜索了類似的線程爲此,但都是我試過!任何人都可以解釋什麼是錯的?
感謝提前:)
哦,非常感謝! –