Private/public functions

A

Andrew Poulos

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
 
M

Michael Winter

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top