使用JAVASCRIPT实现静态物体、静态方法和静态属性

时间:2023-03-09 20:05:17
使用JAVASCRIPT实现静态物体、静态方法和静态属性

Javascript语言的面向对象特征非常弱。其它面向对象语言在创建类时仅仅要使用keywordstatic就可以指定类为静态类,Javascript没有提供static这种keyword。要让Javascript也具有“静态”特性仅仅有靠一些“奇技淫巧”了。

代码中列举了两种静态方法/属性的实现方式。一种是静态类的静态方法和属性,还有一种是非静态类的静态方法和属性,代码说明都写在每行的代码凝视里,这里就不反复了。

/****************************************
* 方法一
* 类、方法、属性都为静态类型
* 不能创建实例
*****************************************/
var Time = {
    today: ‘2009-3-8′, 
    weather: ‘rain’, 
    show: function() {
alert(‘Today is ‘ + this.today); 
}
}; 
 
//静态对象可直接使用,无需创建实例
alert(‘It is ‘ + Time.weather + ‘ today.’); 
Time.show(); 
 
//以下的代码会出错,由于静态类不能创建实例
//var t = new Time();
//t.show();
 
/****************************************
* 方法二
* 普通对象,同一时候拥有静态和非静态属性、方法
* 能够用实例化
* 注意:
*   1.静态方法/属性使用类名訪问
*   2.非静态方法/属性使用实例名訪问
*****************************************/
function Person(name) {
//非静态属性
this.name = name; 
//非静态方法
this.show = function() {
alert(‘My name is ‘ + this.name + ‘.’); 
}
}
//加入静态属性。人都是一张嘴
Person.mouth = 1; 
//加入静态方法。哇哇大哭
Person.cry = function() {
alert(‘Wa wa wa …’); 
}; 
//使用prototypekeyword加入非静态属性,每一个人的牙可能不一样多
Person.prototype.teeth = 32; 
 
//非静态方法必须通过类的实例来訪问
var me = new Person(‘Zhangsan’); 
//使用非静态方法、属性
me.show(); 
alert(‘I have ‘ + me.teeth + ‘ teeth.’); 
//使用静态方法、属性
Person.cry(); 
alert(‘I have ‘ + Person.mouth + ‘ mouth.’);
//
var p=new Person("x");
alert(p.mouth);//回显示没有定义
p.cry();//会显示Uncaught TypeError: Object #<Person> has no method 'cry'
能够发现,实例对象没法訪问类的静态方法和属性。须要訪问仅仅能使用类名

<span style="color:#333333;">function Person(name){
this.name=name;
this.show=function(){
alert("My Name is "+this.name);
};
}; Person.mouth=1;
Person.cry=function(){
alert("wa wa");
}
Person.prototype.teeth=32; var p=new Person("x");
alert(Person["mouth"]);//1
p["show"]();//My name is x</span>


在Jquery中能够这样使用对象的静态方法和属性:
var arr=new Array();
arr["push"]("x");
alert(arr["length"]);//1

欢迎大家补充讨论,共同进步!