简体   繁体   English

全局对象内定义的类中的Javascript静态方法

[英]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.

相关问题 无法调用在javascript中的对象内部定义的方法 - Unable to call a method defined inside an object in javascript 如何在类静态方法中创建一个对象 - How to create an object inside class static method 在Javascript中的类的其他静态方法中调用静态方法 - Call a static method inside other static method of a class in Javascript JavaScript 全局 object 浏览器未定义 - JavaScript global object browser not defined 自实例化静态javascript类方法内部的不良做法? - Self instantiate inside static javascript class method a bad practice? 我可以在JavaScript窗口全局对象中定义的某个对象中找到JQuery函数吗? - Can I find a JQuery function inside some object defined into the JavaScript window global object? JavaScript:如何在超类上调用 STATIC 方法,但该方法未在派生的 class 上定义? - JavaScript: How to call STATIC method on superclass but the method isnot defined on the derivated class? 从父类中的静态方法访问子类中定义的属性 - javascript - Access to property defined in child class from static method in the parent class - javascript 在 javascript class 上使用 static 方法 - using static method on javascript class Javascript 对象类未定义错误 - Javascript object Class is not defined Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM