访问“公共”来自“私有”的方法JavaScript 类中的方法
有没有办法从类中的“私有”函数调用“公共”javascript函数?
查看下面的类:
function Class()
{
this.publicMethod = function()
{
alert("hello");
}
privateMethod = function()
{
publicMethod();
}
this.test = function()
{
privateMethod();
}
}
这是我运行的代码:
var class = new Class();
class.test();
Firebug 给出此错误:
publicMethod 未定义:[Break on this error] publicMethod();
是否有其他方法来调用 publicMethod()在 privateMethod() 中而不访问全局类变量 [即 class.publicMethod()]?
Is there a way to call "public" javascript functions from "private" ones within a class?
Check out the class below:
function Class()
{
this.publicMethod = function()
{
alert("hello");
}
privateMethod = function()
{
publicMethod();
}
this.test = function()
{
privateMethod();
}
}
Here is the code I run:
var class = new Class();
class.test();
Firebug gives this error:
publicMethod is not defined: [Break on this error] publicMethod();
Is there some other way to call publicMethod() within privateMethod() without accessing the global class variable [i.e. class.publicMethod()]?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在构造函数的范围内保存一个变量来保存对
this
的引用。请注意:在您的示例中,您在
privateMethod = function()
使privateMethod
全局化之前省略了var
。我在这里更新了解决方案:You can save off a variable in the scope of the constructor to hold a reference to
this
.Please Note: In your example, you left out
var
beforeprivateMethod = function()
making thatprivateMethod
global. I have updated the solution here:接受的答案可能会产生不良副作用,即在每个实例中都会创建
publicMethod
、test
和privateMethod
的单独副本。避免这种情况的习惯用法是:换句话说,您需要将
this
作为参数传递给私有函数。作为回报,您将获得一个true原型,而不必使用其自己版本的私有和公共函数来污染每个实例。The accepted answer has the possibly undesirable side effect that separate copies of
publicMethod
,test
, andprivateMethod
will be created in each instance. The idiom for avoiding this is:In other words, you need to pass the
this
to the private function as an argument. In return, you get a true prototype without having to pollute each instance with its own versions of the private and public functions.torazaburo的答案是最好的,因为它避免了创建私人成员的多个副本。我很惊讶克罗克福德根本没有提到这一点。或者,根据您喜欢的声明公共成员函数的语法,您可以这样做:
torazaburo's answer is the best one, as it avoids creation of multiple copies of the private members. I'm surprised that Crockford doesn't mention it at all. Alternately, depending on the syntax you prefer for declaring public member functions, you could do this:
这种方法不是可取的吗?但我不确定
Is this approach not a advisable one? I am not sure though