Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "this" in static methods

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.

like image 622
Matteo Pagliazzi Avatar asked Jun 28 '12 16:06

Matteo Pagliazzi


2 Answers

In reality there is no methods or static methods in js, there's just functions that are assigned to object properties (functions being objects as well) and they all work the same way. Since you are calling it like User.b(), this will be User for the call.

User.b = function() {
    return this.a();
}
like image 173
Esailija Avatar answered Sep 23 '22 19:09

Esailija


The only thing that determines the context of the function is how you call it.

If you call it using a plain identifier (a function name, a variable or a property), the context will be the global window object:

someFunction();

If you call it using a period to access an object member, the context will be the object:

someObject.someFunction();

If you copy a member from an object to a variable, there is no connection to the object any more, and it will be called with window as context:

var x = someObject.someFunction;
x();

If you assign a function as a property to an object, and call it using the object, the context will be the object:

someObject.x = someFunction;
someObject.x();

For your specific case, User is a function, which also is an object.

If you call the function using User.b, its context will be the User object, which happens to be a function in this case. From within the function you can still use this to access the context:

User.b = function(){
  return this.a();
}
like image 37
Guffa Avatar answered Sep 24 '22 19:09

Guffa