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

How to use static methods in javascript

coldplay.xixi
Release: 2023-01-05 16:13:16
Original
2711 people have browsed it

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(); //报错
Copy after login

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.');
  }
}
Copy after login

Instance method

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

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!

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