SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Evangelist anjanesh's Avatar
    Join Date
    Jun 2004
    Location
    Mumbai
    Posts
    447
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Private class methods

    Hi

    Is it not possible to create a private method in an object ( which is essentially a function ) ?
    Code JavaScript:
    function foo1()
     {
            this.m = 0;
     
            function foo2()
             {
                    this.m = 2;
             }
     
            this.foo3 = function()
             {
                    this.m = 3;
             }
     
            foo2();
     }
     
    var f = new foo1();
    alert(f.m);
    f.foo3();
    alert(f.m);
    displays 0, 3 when I thought it would display 2, 3.

    Thanks
    Anjanesh

  2. #2
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Are you looking for something like this?
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function foo()
     {
            var m = 2;
     
            function foo2()
             {
                    this.m =function(){alert(m)}
    				this.count =function(){m++}
             }
     
     
            return new foo2();
     }
    function caller() 
    {
    var f = new foo();
    f.m();
    f.count()
    f.m();
    }
    </script>
    </head>
    <body>
    <button onclick="caller() ">click</button>
    </body>
    </html>

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Inner function don't have "this", you must pass it explicitly. Try replacing "foo2()" with "foo2.call(this)".


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
  •