日期:2014-05-16 浏览次数:20457 次
/*****************************************
方法一* 类、方法、属性都为静态类型* 不能创建实例*****************************************/
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 …’); };
//[color=red]使用prototype关键字添加非静态属性,每个人的牙可能不一样多[/color]
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.’);