简体   繁体   English

JavaScript使类的方法静态且可用于其实例

[英]JavaScript make a class's method static and available to its instances

How can you make a class's method static ( available on the class itself ) and accessible from its instances in JavaScript? 如何使类的方法静态( 可在类本身上使用 )并从JavaScript中的实例访问?

class MyClass {
    constructor() {}
    method() {}
}

const myInstance = new MyClass();

myInstance.method(); // calling from instance
MyClass.method(); // calling from class

You can use the static keyword to do so. 您可以使用static关键字来这样做。

class A {
    constructor(){}
    static method(){}
}

const x = new A();

EDIT: 编辑:

x.constructor.method(); // this is possible
A.method();

In Javascript, static methods are bound to class and not instances, so they can only be called by atleast using the constructor. 在Javascript中,静态方法是绑定到类的,而不是实例的,所以只能由构造函数至少调用它们。 A.prototype handles instance methods whereas the function A handles it's attributes. A.prototype处理实例方法,而函数A处理其属性。

Static method calls are made directly on the class and are not callable on instances of the class. 静态方法调用直接在类上进行,而不能在类的实例上进行调用。 But you can achieve the calls for static members from inside an instance. 但是您可以从实例内部实现对静态成员的调用。

Using syntax: 使用语法:

this.constructor.staticfunctionName();

ES6 Class Example : ES6 Class Example

class MyClass {
    constructor() {}
    static staticMethod() {
        console.log('Static Method');
    }
}
MyClass.staticVar = 777;

var myInstance = new MyClass();
// calling from instance
myInstance.constructor.staticMethod();
console.log('From Inside Class : ',myInstance.constructor.staticVar);

// calling from class
MyClass.staticMethod();
console.log('Class : ', MyClass.staticVar);

For ES5 Function Classes refer to my answer . 对于ES5 Function Classes 请参阅我的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM