阅读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