The so-called static method is a method that belongs to all instances of the class and does not belong to a specific instance of the class. It can only be called by the class, but not directly by the class instance.
In C #, it is easy to declare a static method. You only need a keyword: static.
In JavaScript, if we are sure we need a method that is manipulated by a class, what should we do?
First, let's look at an example to illustrate how to expand the class as follows:
Var Employee = function (name, dept ){
This. name = name | "none ";
This. dept = dept | "general ";
}
Employee. prototype. toString = function () {// toString is a common method of the Employee class
Return this. name + "&" + this. dept;
} The Employee is running. prototype. when toString is used, there is no toString function. The system checks the function. If not, the toString function is automatically created and the toString object is directed to an anonymous function, this anonymous function can be considered as the function body of the toString function.
Note that the prototype keyword has a very high position in JavaScript and is the core of JavaScript's implementation of some important mechanisms!
Currently, this toString method is not a static method. It can be used for class instances. First, this method is described for comparison with the static method.
Add a static show method for the Employee as follows:
Employee. show = function (ep) {// show is the static method of the Employee class
Alert (ep. toString ());
} We can find that the difference between declaring a conventional method and a static method lies only in the use of the prototype keyword.
The following is a complete example:
<Script type = "text/javascript">
// Create a class named "Employee" as the base class.
Var Employee = function (name, dept ){
This. name = name | "none ";
This. dept = dept | "general ";
}
Employee. prototype. toString = function () {// toString is a common method of the Employee class
Return this. name + "&" + this. dept;
}
Employee. show = function (ep) {// show is the static method of the Employee class
Alert (ep. toString ());
}
Var ep = new Employee ("fanrong", "Technology Department ");
Employee. show (ep); // It can only be called by classes and cannot be called by instance objects.
// Ep. show (ep); // an error is returned.
</Script> static methods are a feature of OO programming and are useful in many scenarios.