有没有一种方法可以从类中的“私有(private)”函数调用“公共(public)”javascript 函数?
查看下面的类:
function Class()
{
this.publicMethod = function()
{
alert("hello");
}
privateMethod = function()
{
publicMethod();
}
this.test = function()
{
privateMethod();
}
}
这是我运行的代码:
var class = new Class();
class.test();
Firebug 给出了这个错误:
publicMethod 未定义:[出现此错误时中断] publicMethod();
是否有其他方法可以在不访问全局类变量的情况下在 privateMethod() 中调用 publicMethod() [即class.publicMethod()]?
最佳答案
您可以在构造函数的范围内保存一个变量来保存对 this
的引用。
请注意:在您的示例中,您在 privateMethod = function()
之前遗漏了 var
使 privateMethod
全局。我在这里更新了解决方案:
function Class()
{
// store this for later.
var self = this;
this.publicMethod = function()
{
alert("hello");
}
var privateMethod = function()
{
// call the method on the version we saved in the constructor
self.publicMethod();
}
this.test = function()
{
privateMethod();
}
}
关于javascript - 从javascript类中的 "Public"方法访问 "Private"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2703582/