SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2006
    Posts
    72
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Private methods in the JavaScript object model

    I have some methods which would technically be private that I need to call from the public methods of an object. I am not concerned about public/private per se (they can all be public) but will the 'private' method still recognize the 'this.attribute' notation or do I have to pass a reference to the object to a stand alone function and work with it that way.

    In other words, does something like this work?

    somevalue = objFoo.myFunction1();


    function myFunction1(){
    return this.myFuntion2()
    }

    function myFunction2(){
    return this.mainvalue;
    }

  2. #2
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No, try this instead
    Code:
    /**
     * Constructor
     */
    function Foo() {
        
    }
    
    /**
     * Method 1
     */
    Foo.prototype.method1 = function() {
        this.method2();
    }
    
    /**
     * Method 2
     */
    Foo.prototype.method2 = function() {
    
    }
    There are other ways to do OOP, this is only one way to do it. If it is important to have certain properties and methods as private, then use the following approach:
    Code:
    function Foo() {
        var privateProperty = "private";
    
        var privateMethod = function() {
            alert(privateProperty);
        }
    
        return {
            publicMethod: function() {
                /** Note that keyword this is not used, since it is 
                 * calling a (nested) function
                 */
                privateMethod();
           }
        }
    }
    
    var foo = new Foo();
    
    foo.publicMethod();


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •