By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,384 Members | 1,794 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,384 IT Pros & Developers. It's quick & easy.

Private/public functions

P: n/a
I having some trouble understanding how to make functions private

I have created an instance of an object using a constructor function and
there are 4 prototypes:

Comm = function() {
//blah
}

Comm.prototype.get = function() {
//blah
}

Comm.prototype.set = function() {
//blah
}

Comm.prototype.start = function() {
//blah
}

Comm.prototype.end = function() {
//blah
}

foo = new Comm();

There are 8 "supporting" functions (additional functions that each of
the prototypes may call). How can I make the "supporting" functions
private yet still available to all prototypes? That is, only a prototype
may call a "supporting" function.

Andrew Poulos
Oct 12 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 12/10/2005 14:19, Andrew Poulos wrote:

[snip]
I have created an instance of an object using a constructor function and
there are 4 prototypes:
[snip]
There are 8 "supporting" functions (additional functions that each of
the prototypes may call). How can I make the "supporting" functions
private yet still available to all prototypes? [...]


It depends on what scope those function should have.

If they would be private instance methods (in other languages), then you
can't do what you'd want through the prototype object - the methods
would need to be added in the constructor:

function MyObject() {
function myPrivateMethod() {
}

this.myMethod = function() {
};
}

If they would be private static (class) methods, then you can introduce
another scope in which you define the supporting functions, and from
which you return the constructor function:

var MyObject = (function() {
function myPrivateStaticMethod() {
}

function constructor() {
}
constructor.prototype.myMethod = function() {
};

return constructor;
})(); /* Notice the call at the end of this expression. */

You can call the inner constructor function whatever you want, of course.

See Douglas Crockford's and Richard Cornford's treatises on private
members[1] and private static members[2] for a more in-depth description.

Hope that helps,
Mike
[1] Private members
<URL:http://www.crockford.com/javascript/private.html>
[2] Private static members
<URL:http://www.litotes.demon.co.uk/js_info/private_static.html>

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 12 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.