封裝
1.不合理:構造函數模式的問題
構造函數方法很好用,但是存在一個浪費內存的問題。
請看,我們現在為Cat對象添加一個不變的屬性type(種類),再添加一個方法eat(吃)。那么,原型對象Cat就變成了下面這樣:
function Cat(name,color){
this.name = name;
this.color = color;
this.type = "貓科動物";
this.eat = function(){alert("吃老鼠");};
}
var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat ("二毛","黑色");
alert(cat1.type); // 貓科動物
cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //false
2.合理的方式:Prototype模式
function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "貓科動物";
Cat.prototype.eat = function(){alert("吃老鼠")};
var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat("二毛","黑色");
alert(cat1.type); // 貓科動物
cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //true
3.Prototype模式的驗證方法
3.1.isPrototypeOf()
這個方法用來判斷,某個proptotype對象和某個實例之間的關系。
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
3.2 .hasOwnProperty()
每個實例對象都有一個hasOwnProperty()方法,用來判斷某一個屬性到底是本地屬性,還是繼承自prototype對象的屬性。
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
3.3 .in運算符
in運算符可以用來判斷,某個實例是否含有某個屬性,不管是不是本地屬性。in運算符還可以用來遍歷某個對象的所有屬性。
alert("name" in cat1); // true
alert("type" in cat1); // true
for(var prop in cat1) { alert("cat1["+prop+"]="+cat1[prop]); }