Home  >  Article  >  Web Front-end  >  Static methods of Class class in ES6

Static methods of Class class in ES6

小云云
小云云Original
2018-01-19 16:42:581554browse

This article mainly introduces the static methods of the Class class in ES6. It briefly summarizes and analyzes the use of static methods and related precautions in the class class in ES6 based on the example form. Friends in need can refer to it. I hope it can help everyone.

I have seen es6 stuff before, but I have forgotten it. Let me summarize:

A class is equivalent to the prototype of an instance. All methods defined in the class will be inherited by the instance. If you add the static keyword before a method, it means that the method will not be inherited by the instance, but will be called directly through the class. This is called a "static method"


class Foo {
  static classMethod() {
    return 'hello';
  }
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

In the above code, the classMethod method of class Foo is preceded by the static keyword, indicating that the method is a static method and can be called directly on class Foo (Foo.classMethod()) instead of calling it on an instance of class Foo. If a static method is called on an instance, an error is thrown indicating that the method does not exist.

Static methods of parent classes can be inherited by subclasses.


class Foo {
  static classMethod() {
    return 'hello';
  }
}
class Bar extends Foo {
}
Bar.classMethod(); // 'hello'

In the above code, the parent class Foo has a static method, and the subclass Bar can call this method.

Related recommendations:

Detailed explanation of the class keyword in ES6

Detailed explanation of the super keyword in ES6 Class

Examples of get and set usage of class class in ES6 javascript

The above is the detailed content of Static methods of Class class in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn