JavaScript私有方法 [英] JavaScript private methods
问题描述
要使用公共方法创建JavaScript类,我会执行以下操作:
To make a JavaScript class with a public method I'd do something like:
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
这样我班级的用户可以:
That way users of my class can:
var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
如何创建可由 buy_food <调用的私有方法
和 use_restroom
方法但不是该类用户的外部方法?
How do I create a private method that can be called by the buy_food
and use_restroom
methods but not externally by users of the class?
换句话说,我希望我的方法实现能够:
In other words, I want my method implementation to be able to do:
Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
但这不起作用:
var r = new Restaurant();
r.private_stuff();
如何将 private_stuff
定义为私有方法所以这两个都适用?
How do I define private_stuff
as a private method so both of these hold true?
我读过 Doug Crockford的写法几次,但看起来不像私有方法可以通过公共方法调用,特权方法可以在外部调用。
I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
推荐答案
你可以做到,但缺点是它不能成为原型的一部分:
You can do it, but the downside is that it can't be part of the prototype:
function Restaurant()
{
var myPrivateVar;
var private_stuff = function() // Only visible inside Restaurant()
{
myPrivateVar = "I can set this here!";
}
this.use_restroom = function() // use_restroom is visible to all
{
private_stuff();
}
this.buy_food = function() // buy_food is visible to all
{
private_stuff();
}
}
这篇关于JavaScript私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!