Home > Web Front-end > JS Tutorial > body text

How to use static methods, attributes and instance attributes of classes in ES6 javascript

php中世界最好的语言
Release: 2017-12-31 11:36:45
Original
1765 people have browsed it

What I bring to you this time is the static methods of classes in ES6 javascript, how to use attributes and instance attributes, this article will give you a good analysis.

The class is equivalent to the prototype of the 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. Instead, it is called directly through the class, which 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
Copy after login

In the above code, there is the static keyword before the classMethod method of class Foo, 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'
Copy after login


In the above code, the parent class Foo has a static method, and the subclass Bar can call this method.
Static methods can also be called from the super object.

class Foo {
  static classMethod() {
    return 'hello';
  }
}
class Bar extends Foo {
  static classMethod() {
    return super.classMethod() + ', too';
  }
}
Bar.classMethod();
Copy after login

I believe you have mastered the method after reading the above introduction. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

Use jQuery to deduplicate and sort arrays

How to use Vue’s automatic Define instructions to complete a drop-down menu

How to use the navigation component react-navigation

The above is the detailed content of How to use static methods, attributes and instance attributes of classes in ES6 javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template