構造函數: function Cat (name ,color){
this.name = name;
this.color = color;
}
//生成實例對象
var cat1 = new Cat('大貓','黃色');
var cat2 = new Cat('小貓','藍色');
構造函數是一個普通的函數,但是內部使用了this變量,對構造函數使用new 運算符,就能生成實例,并且this變量會綁定在實例對象上。
cat1 和 cat2 會自動增加constructor 屬性,指向他們的構造函數。
cat1.constructor == Cat //true;
cat2.constructor == Cat //true;
驗證原型對象與實例對象之間的關系
cat1 instanceof Cat //true
cat2 instanceof Cat //true
每一個構造函數 都會有每一個prototype 屬性 這個對象上的屬性和方法都會被實例對象繼承。
我們要在Cat方法加上一個eat方法和type屬性 ,
function Cat(name,color){
this.name = name;
this.color = color;
this.type ='cat';
this.eat = function(){
alert('eat');
}
}
這樣的話 在每次創建實例對象的時候 type和eat() 方法都是一模一樣的內容,多占用一些內容,這樣不環保,也缺乏效率。
Cat.prototype.type ='cat';
Cat.protitype.eat = function(){
alert('eat');
}
把要增加的不變屬性和方法加到prototype上,可以使這些在內存中只生成一次。
isPrototypeOf() 配合Protype屬性,來判斷某個Protype屬性和某個實例對象的關系
Cat.prototype.isProtypeOf(cat1);//true
Cat.protype.isProtypeOf(cat2);//true;
hasOwnProperty()
每一個實例對象都有一個hasOwnProperty()方法,來判斷某個屬性是否屬于示例對象還是繼承與構造函數。
cat1.hasOwnProperty('name');//true;
cat2.hasOwnProperty('type');//false
in運算符
in運算符可以用來判斷,某個實例是否含有某個屬性,不管是不是自身屬性
‘name’ in cat1 //true;
'type' in cat1 //true;
in運算符還可以用來遍歷某個對象的所有屬性。