Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...