Private/public functions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Poulos

    Private/public functions

    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
  • Michael Winter

    #2
    Re: Private/public functions

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

    [snip]
    [color=blue]
    > I have created an instance of an object using a constructor function and
    > there are 4 prototypes:[/color]

    [snip]
    [color=blue]
    > 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? [...][/color]

    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 myPrivateStatic Method() {
    }

    function constructor() {
    }
    constructor.pro totype.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.c om/javascript/private.html>
    [2] Private static members
    <URL:http://www.litotes.dem on.co.uk/js_info/private_static. html>

    --
    Michael Winter
    Prefix subject with [News] before replying by e-mail.

    Comment

    Working...