Javascript object-oriented features of the language is weak, other object-oriented languages when creating a class just use the static keyword to specify the class as a static class, Javascript does not provide a keyword such as static, Javascript also have to make a "static" characteristics only by Some "clever but useless" the.
A code implementations include two kinds of static methods / attributes of a class is a static properties and static methods, static methods and other properties, non-static class code description are written in each line in the code comments, where not repeat.
JAVASCRIPT:
-
/****************************************
-
* method one
-
* Classes, methods, properties are static type
-
* You can not create an instance
-
*****************************************/
-
var time = {
-
today: ‘2009-3-8′,
-
weather: ‘rain’,
-
show: function ( ) {
-
alert ( ‘Today is ‘ + this. today );
-
}
-
};
-
-
// static object can be used directly, without having to create an instance
-
alert ( ‘It is ‘ + Time. weather + ‘ today.’ );
-
Time. show ( );
-
-
// The following code will be wrong, because the static class can not create an instance
-
// var t = new Time ();
-
//t.show();
-
-
/****************************************
-
* Method Two
-
* Ordinary objects, have both static and non-static properties, methods
-
* Can be instantiated
-
* Note:
-
* 1. Static method / property using the class name to access
-
* 2. Non-static method / property using the instance name to access
-
*****************************************/
-
function Person ( name ) {
-
// non-static properties
-
this. name = name;
-
// non-static method
-
this. show = function ( ) {
-
alert ( ‘My name is ‘ + this. name + ‘.’ );
-
}
-
}
-
// add static properties, but every man a mouth
-
Person. mouth = 1;
-
// add a static method, cried
-
Person. cry = function ( ) {
-
Alert ( 'Wa Wa Wa ...' ) ;
-
};
-
// add non-static properties using the prototype keyword, each person's teeth may not be as much
-
Person. prototype. teeth = 32;
-
-
// non-static methods must be accessed through instances of the class
-
var me = new Person ( ‘Zhangsan’ );
-
//使用非静态方法、属性
-
me. show ( );
-
alert ( ‘I have ‘ + me. teeth + ‘ teeth.’ );
-
//使用静态方法、属性
-
Person. cry ( );
-
alert ( ‘I have ‘ + Person. mouth + ‘ mouth.’ );
转载于:https://www.cnblogs.com/200831856/archive/2009/09/15/javascript_static_1.html