您的位置:首页 > Web前端 > JavaScript

JavaScript面向对象

2011-04-04 14:46 204 查看
/****************************************
* 方法一
* 类、方法、属性都为静态类型
* 不能创建实例
*****************************************/
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 …’);
};
//使用prototype关键字添加非静态属性,每个人的牙可能不一样多
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.’);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: