Home  >  Article  >  Web Front-end  >  What are JavaScript class static methods?

What are JavaScript class static methods?

WBOY
WBOYOriginal
2022-04-06 10:43:272676browse

The static method of a class in JavaScript is a method modified with the static keyword, also called a class method; the static method can be called through "class name. method name" before instantiating the object, and the static method cannot be used in the object Called on, it can only be called within a class.

What are JavaScript class static methods?

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

javascript class static method

Static method is a method modified with the static keyword, also called a class method. It belongs to the class, but does not belong to the object. You can pass the class name before instantiating the object. .Method name calls a static method.

Static methods cannot be called on instances of a class, but should be called through the class itself. Cannot be called on an object, only within a class.

The example is as follows:

class Tripple {
    static tripple(n = 1)  {
        return n * 3;
    }
}
// 正确用法
console.log(Tripple.tripple());// 3
// 如下为错误用法
let tp = new Tripple();
console.log(tp.tripple());//  'tp.tripple 不是一个函数'.

An instance object will report an error when calling a static method:

What are JavaScript class static methods?

Related recommendations: javascript learning tutorial

The above is the detailed content of What are JavaScript class static methods?. 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