JavaScript private methods
Posted
by Wayne Kao
on Stack Overflow
See other posts from Stack Overflow
or by Wayne Kao
Published on 2008-09-11T01:12:39Z
Indexed on
2010/03/17
1:41 UTC
Read the original article
Hit count: 362
JavaScript
|oop
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();
How do I create a private method that my public buy_food and use_restroom methods can call but that users of the class can't call externally.
In other words, I want my method implementation to be able to do:
Restaurant.prototype.use_restroom = function()
{
this.private_stuff();
}
But this shouldn't work:
var r = new Restaurant();
r.private_stuff();
How do I define private_stuff as a private method so both of those hold true?
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.
© Stack Overflow or respective owner