Javascript“this”在静态方法 [英] Javascript "this" in static methods

查看:651
本文介绍了Javascript“this”在静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

  User = function(){} 

.a = function(){
returntry;
}

User.b = function(){

}


从User.b()我可以调用User.a()使用:

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

但不使用,因为它不是用户的实例)和User.b()是类似静态方法)。



我想做的是能够从User调用User.a()。 b()不知道哪个是主函数,在这种情况下是User。



类似这样在静态方法中使用。


<实际上,在js中没有方法或静态方法,只有分配给对象属性(函数也是对象)的函数,它们都工作相同办法。因为你像 User.b()这样调用将 User for the call。

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


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.

解决方案

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

这篇关于Javascript“this”在静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆