快速提问。
我已经(适度)使用 jQuery 很长时间了,但我从来没有真正体验过“类”(松散地使用)。
这是我的测试“类”,位于http://jsfiddle.net/TxUs2/ .
function MyClass(prop) {
this.prop = prop;
var init = function()
{
alert(this.prop);
}
init();
}
var myClass = new MyClass();
我希望 init() 方法是私有(private)的。请有人简要解释一下为什么我无法通过私有(private)方法访问公共(public)属性?
我假设它与“this”有关,本质上是从方法内部指向方法本身,而不是包含函数(或“类”)。我该如何解决这个问题?
非常感谢。
编辑:非常感谢您的所有投入。所有答案都很棒。 :)
最佳答案
问题是当您调用 init
时它在没有上下文的情况下被调用,因此 this
不引用 MyClass
的实例.您可以通过保存对 this
的引用来解决此问题在构造函数中,调用 init
在 this
的背景下或绑定(bind) init
至 this
:
保存对
this
的引用:function MyClass(prop) { this.prop = prop; var that = this; var init = function() { alert(that.prop); } init(); }
调用
init
在this
的背景下:init.call(this);
绑定(bind)
init
至this
(这使得每个调用的行为都像init.call(this)
):var init = function () { alert(this.prop); }.bind(this); init();
关于Javascript:无法从私有(private)方法访问公共(public) Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22762374/