封裝
1.不合理:構(gòu)造函數(shù)模式的問(wèn)題
構(gòu)造函數(shù)方法很好用,但是存在一個(gè)浪費(fèi)內(nèi)存的問(wèn)題杠步。
請(qǐng)看,我們現(xiàn)在為Cat對(duì)象添加一個(gè)不變的屬性type(種類(lèi)),再添加一個(gè)方法eat(吃)次坡。那么,原型對(duì)象Cat就變成了下面這樣:
function Cat(name,color){
this.name = name;
this.color = color;
this.type = "貓科動(dòng)物";
this.eat = function(){alert("吃老鼠");};
}
var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat ("二毛","黑色");
alert(cat1.type); // 貓科動(dòng)物
cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //false
2.合理的方式:Prototype模式
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "貓科動(dòng)物";
Cat.prototype.eat = function(){alert("吃老鼠")};
var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat("二毛","黑色");
alert(cat1.type); // 貓科動(dòng)物
cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //true
3.Prototype模式的驗(yàn)證方法
3.1.isPrototypeOf()
這個(gè)方法用來(lái)判斷画畅,某個(gè)proptotype對(duì)象和某個(gè)實(shí)例之間的關(guān)系砸琅。
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
3.2 .hasOwnProperty()
每個(gè)實(shí)例對(duì)象都有一個(gè)hasOwnProperty()方法,用來(lái)判斷某一個(gè)屬性到底是本地屬性轴踱,還是繼承自prototype對(duì)象的屬性症脂。
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
3.3 .in運(yùn)算符
in運(yùn)算符可以用來(lái)判斷,某個(gè)實(shí)例是否含有某個(gè)屬性淫僻,不管是不是本地屬性诱篷。in運(yùn)算符還可以用來(lái)遍歷某個(gè)對(duì)象的所有屬性。
alert("name" in cat1); // true
alert("type" in cat1); // true
for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }