Home >Web Front-end >JS Tutorial >How to use static methods in javascript

How to use static methods in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-30 15:45:212746browse

How to use static methods in JavaScript: Defining a function actually defines a class [class], the code is [Person.say=function(){console.log('I am a Person,I can say.')}].

How to use static methods in javascript

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

How to use static methods in javascript:

static method

Person.say=function(){
    console.log('I am a Person,I can say.')
};
Person.say(); //正常运行
var carl=new Person;
carl.say(); //报错

We added a say method to the Person class, which is on the class , so, it is actually a static method.

Static method: Static methods cannot be called on instances of a class, but should be called through the class itself.

Class (class) defines static methods through the static keyword. The above definition of the Person.say method is equivalent to:

class Person {
  static say() {
    return console.log('I am a Person, I can say.');
  }
}

Instance method

Person.prototype.getName=function(name){
    console.log('My name is '+name);
}
Person.getName('Carl'); //报错
var carl=new Person;
carl.getName('Carl'); //正常运行

getName This method is actually on the prototype. Only when an instance is created, can the instance be passed for a visit.

Related free learning recommendations: javascript video tutorial

The above is the detailed content of How to use static methods in javascript. 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