2013-08-05 57 views
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'的消息,但它返回另一個!

我搜索了類似的線程爲此,但都是我試過!任何人都可以解釋什麼是錯的?

感謝提前:)

回答

6

util.inherits具有好不尷尬super_ ......無論如何,這應該工作:

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

不過說真的,

var super_ = Request.prototype; 

然後語法變得幾乎方便:

super_.process.call(this, callback); 
+0

哦,非常感謝! –