Alex Rivera | Logout

Javascript "this" in static methods

Asked 2012-06-28T16:30:40.163
8

I have a code like that:

User = function(){}

User.a = function(){
  return "try";    
}

User.b = function(){

}

​ From User.b() I can call User.a() using:

User.b = function(){
    return User.a();
    }

but not using this since it's not an instance of user (User.a() and User.b() are something like "static methods").

What i want to do is to be able to call User.a() from User.b() without knowing which is the main function, in this case User.

Something like this to be used in static methods.

Edit
Report

1 Answer

0

You don't have normal inheritance in javascript. I guess you are trying to do something like this:

User = function(){
    this.a= function(){
         return 'try';
    }
    this.b= function(){
        return this.a();
    }
}

This way User becomes a constructor. Each new instance of User will have acces to these methods. So if you want to create a new instance of the User class, you can use the new keyword:

var client= new User()

and then you'll have access to all the methods from user using client

client.b() //returns 'try'
answered 2012-06-28T16:37:21.093

Your Answer