2011-12-17 108 views
2

有什麼方法可以在構造函數中訪問類變量嗎?如何訪問構造函數中的類變量? (node.js OOP)

var Parent = function() { 
    console.log(Parent.name); 
}; 
Parent.name = 'parent'; 

var Child = function() { 
    Parent.apply(this, arguments); 
} 
require('util').inherits(Child, Parent); 
Child.name = 'child'; 

即父類的構造應登錄「父母」和孩子的構造應登錄「孩子」基於一個在每類中的一些類變量。

上面的代碼不能像我期望的那樣工作。

回答

1

這是香草JS:

var Parent = function() { 
    console.log(this.name); 
}; 
Parent.prototype.name = 'parent'; 

var Child = function() { 
    Parent.apply(this, arguments); 
} 

Child.prototype = new Parent(); 
Child.prototype.constructor = Child; 
Child.prototype.name = 'child'; 

var parent = new Parent(); 
var child = new Child(); 

utils.inherits只是簡化了

Child.prototype = new Parent(); 
Child.prototype.constructor = Child; 

util.inherits(Child, Parent); 
+0

utils.inherits不超過描述(指沒有實例子類)。 – 2011-12-17 09:30:17