要使用公共方法创建JavaScript类,我需要执行以下操作:
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
这样,我班的用户可以:
var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
如何创建一个私有方法,该私有方法可以由buy_food
和use_restroom
方法调用,但不能由该类的用户外部调用?
换句话说,我希望我的方法实现能够做到:
Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
但这不起作用:
var r = new Restaurant();
r.private_stuff();
如何将其定义private_stuff
为私有方法,使两者都适用?
我已经读过Doug Crockford的文章几次,但似乎公共方法不能调用“私有”方法,而外部可以调用“特权”方法。
There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:
As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.