很多javascript新手都覺得javascript的類、委託、事件很神秘,當你看下面幾段代碼後,你會覺得它也不過如此,和其他的物件導向的語言沒什麼差別。
javascript中的類:
javascript中的類
function Person(name, age) {
this._name = name;
this._age = age;
//對應Name的Get,Set方法,這個和Java的屬性寫法很像。
this.getName = function() {
return this._name
};
this.setName = function(name) {
this._name = name;
}
//對應Age的Get,Set方法
this.getAge = function() {
return this._age;
}
this.setAge = function(age) {
this._age = age;
}
//顯示Person的資訊方法
this.show = function() {
alert("Name:" + this.getName() + "; Age:" + this.getAge());
}
}
//空構造方法
var p1 = new Person();
p1.setName("Southsea");
p1.setAge(23);
p1.show();
//帶參的構造方法
var p2 = new Person("Southsea", 23);
p2.show();
//註:Javascript中沒有真正的方法重載
看起來很簡單吧。
下面我們把Pererson類的show方法加一個參數,讓它具有委託的功能。
委託
function Person(name, age) {
this._name = name;
this._age = age;
//對應Name的Get,Set方法,這個和Java的屬性寫法很像。
this.getName = function() {
return this._name
};
this.setName = function(name) {
this._name = name;
}
//對應Age的Get,Set方法
this.getAge = function() {
return this._age;
}
this.setAge = function(age) {
this._age = age;
}
//顯示Person的資訊方法
this.show = function(delegate) {
if (delegate) {
delegate(this);
}
}//只有這段與上面的不同。
}
//訂閱Person類的show
function showPerson(p) {
alert("Name:" + p.getName() + "; Age:" + p.getAge());
}
var p = new Person("Southsea", 23);
p.show(showPerson); //別寫成p.show(showPerson());哦
javascript中的事件
事件
function Person(name, age) {
this._name = name;
this._age = age;
//對應Name的Get,Set方法,這個和Java的屬性寫法很像。
this.getName = function() {
return this._name
};
this.setName = function(name) {
this._name = name;
}
//對應Age的Get,Set方法
this.getAge = function() {
return this._age;
}
this.setAge = function(age) {
this._age = age;
}
this.onShow = null;//加了onshow事件
//顯示Person的資訊方法
this.show = function() {
if (this.onShow) {
this.onShow(this);
}
}
}
//訂閱Person類的show
function showPerson(p) {
alert("Name:" + p.getName() + "; Age:" + p.getAge());
}
var p = new Person("Southsea", 23);
p.onShow = showPerson; //千萬別寫成p.onShow = showPerson();
p.show();
委託和事件都看起來很簡單吧。
javascript的動態類,它的格式是與JSON一樣的。
動態類
var person = {
"Name": "Southsea",
"Age": 23, "show": function() {
alert("Name:" + person.Name + "; Age:" + person.Age);
}
};
person.show();
上面的幾段代碼是不是看起來很簡單呀,希望這編文章對你有一定的協助。。。