標籤:js
基於原型的建立雖然可以有效地完成封裝,但是依然存在如下問題:
1.無法通過建構函式來設定屬性值
2.當屬性中有參考型別變數時,可能存在變數值重複
function Person(){
}
Person.prototype = {
constructor:Person,
name:"Leon",
age:30,
friends:["Ada","Chris"],
say:function(){
alert(this.name+"["+this.friends+"]");
}
}
var p1 = new Person();
p1.name = "John";
p1.say(); //John[Ada,Chris]
var p2 = new Person();
p2.say(); //Leon[Ada,Chris]
p1.friends.push("Mike");
//此時原型中就多了一個Mike,這就是原型所帶來的第二個問題
p2.say(); //Leon[Ada,Chris,Mike]
/**為瞭解決原型所帶來的問題,我們可以通過組合建構函式和原型來實現對象的建立
* 將屬性在建構函式中定義,將方法在原型中定義
*/
function Person(name,age,friends){
//屬性在建構函式中定義
this.name = name;
this.age = age;
this.friends = friends;
}
Person.prototype = {
constructor:Person,
//方法在原型中定義
say:function(){
alert(this.name+"["+this.friends+"]");
}
}
//此時所有的屬性都是儲存在自己的空間中
var p1 = new Person("Leon",23,["Ada","Chris"]);
p1.name = "John";
p1.friends.push("Mike");
p1.say(); //John[Ada,Chris,Mike]
var p2 = new Person("Ada",33,["Leon"]);
p2.say(); //Ada[Leon]
為了讓定義的方式更加符合Java的需求,就把定義方法的原型代碼放置到Person這個建構函式中
function Person(name,age,friends){
//屬性在建構函式中定義
this.name = name;
this.age = age;
this.friends = friends;
//不能使用重寫的方式定義
/*Person.prototype = {
constructor:Person,
//方法在原型中定義
say:function(){
alert(this.name+"["+this.friends+"]");
}
}*/
if(typeof Person.prototype.say){
//但是這也會引起一個問題:那就是每new一個對象,say方法就定義一次 所以我們要在上面加上if條件
Person.prototype.say = function(){
alert(this.name+"["+this.friends+"]");
}
}
}
原創文章如轉載,請註明出處,本文首發於csdn網站:http://blog.csdn.net/magneto7/article/details/24934149