[英]Javascript static method in class defined inside global object
I know Javascript doesn't have classes in the same way that traditional OOP languages do and that a "class" definition such as the following, is merely a function object that can be used with the new
keyword: 我知道Javascript不像传统的OOP语言那样具有类,并且诸如以下的“类”定义仅仅是可以与
new
关键字一起使用的函数对象:
function MyClass(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
}
What I'm wondering is, if I define a global object (to avoid polluting the namespace) and define my classes inside this object, can I define a static method for my class in a nicer way than this: 我想知道的是,如果我定义一个全局对象(以避免污染名称空间)并在该对象内定义我的类,那么我可以用比这更好的方式为我的类定义一个静态方法吗:
var MyObject = {
MyClass: function(){
this.a = function(){ /* Do something */ }; // Public function
function b(){ /* Do something */ }; // Private function
},
}
MyObject.MyClass.MyStaticMethod = function(){ /* Do something */ };
I was thinking something along the lines of defining MyStaticMethod
inside the MyClass
function scope - is this possible? 我在考虑在
MyClass
函数范围内定义MyStaticMethod
-这可能吗?
You can do this: 您可以这样做:
var MyObject = {
MyClass: function(){
this.a = function(){ /* Do instance-y stuff */ };
MyClass.MyStaticMethod = function(){ /* Do static-y stuff */ };
}
}
but I think it's a bad idea. 但我认为这是个坏主意。 In general, I think it's better practice (because it's more readable) to define both static and instance methods OUTSIDE of the constructor.
总的来说,我认为最好在构造函数的外部定义静态方法和实例方法(因为它更具可读性)。 As in:
如:
function MyClass() { /* Do initialization stuff */ }
MyClass.prototype.a = function() { /* Do instance-y stuff */ }
MyClass.MyStaticMethod = function() { /* Do static-y stuff */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.