閱讀JavaScript的prototypical inheritance model了一下後,我改變我的構造一類的風格從更好的方式來訪問私有成員的Javascript
var Some_Class = function() {
this.public_method = function() {
};
(function() {
// constructor
}).call(this)
}
到
var Some_Class = function() {
(function() {
// constructor
}).call(this)
}
Some_Class.prototype.public_method = function() {
};
雖然我明白,這是一個良好的做法,但我不允許從公共方法訪問私人方法
var Some_Class = function() {
var private_member = 'whatever';
(function() {
// constructor
}).call(this)
}
Some_Class.prototype.public_method = function() {
return private_member; // not possible
};
通過文章here(封閉創建構造函數)看完後,然後我來到了這個
var Some_Class = function() {
var private_member = 'whatever',
private_method = function(_some_value) {
// private method implementation
};
if(!arguments.callee.prototype.public_method) {
arguments.callee.prototype.public_method = function() {
private_method.call(this, private_method);
};
}
(function() {
// constructor
}).call(this)
}
然而,什麼是這樣做的缺點?或者如果我想在公共方法中訪問private member,是否有更好的方法?
感謝您澄清,第二個問題...我想這可能是因爲我仍然不太熟悉對象模型,並希望使我的代碼類似於OOP代碼在php/java/other OOP編程語言 – Jeffrey04 2009-06-25 06:32:40