原型鏈
理解 prototype
-
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html
- 理解prototype
然后生成實例function Cat(name,color){ //本地屬性 this.name = name; this.color = color; } //繼承屬性 Cat.prototype.type = "貓科動物"; Cat.prototype.eat = function(){ alert("吃老鼠") };
這時所有實例的type屬性和eat()方法,其實都是同一個內存地址,指向prototype對象,因此就提高了運行效率。var cat1 = new Cat("大毛","黃色"); var cat2 = new Cat("二毛","黑色"); alert(cat1.type); // 貓科動物 cat1.eat(); // 吃老鼠
alert(cat1.eat == cat2.eat); //true
prototype 的驗證幾種方法
1> isPrototypeOf()
- 這個方法用來判斷,某個proptotype對象和某個實例之間的關系。
alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
2> hasOwnProperty()
每個實例對象都有一個hasOwnProperty()方法,用來判斷某一個屬性到底是本地屬性,還是繼承自prototype對象的屬性。
alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false
3> in運算符
in運算符可以用來判斷,某個實例是否含有某個屬性,不管是不是本地屬性。
alert("name" in cat1); // true
alert("type" in cat1); // true
in運算符還可以用來遍歷某個對象的所有屬性。
for(var prop in cat1) {
alert("cat1["+prop+"]="+cat1[prop]);
}