(1)構造函數的簡單介紹
構造函數的特點有:
a.構造函數的首字母大寫;
b.內部使用this,指向生成的對象的實例
c.使用new 創建實例
構造函數的缺點:
所有對象都繼承構造器裏面的方法和屬性,但這些方法和屬性都是獨有的,不是共享的。
下面舉個例子說明:
function Persion() {
this.name='陳志豪';
this.say=function () {
return "hi";
}
}
var man=new Persion();
var woman=new Persion();
woman.name="Kate";
console.log(man.name);//陳志豪
console.log(woman.name);//Kate
console.log(man.name);//陳志豪
console.log(man.say()===woman.say())//true
console.log(man.say===woman.say)//false
console.log(man.say())//這是方法返回的字符串
console.log(man.say)//這是方法
從上面可以看到,js 生成的對象,屬性和方法都是不共享的
(2)prototype的作用
每一個構造函數都有一個prototype屬性,這個屬性是構造函數生成的對象實例的原型對象,即基礎父類。這個prototype對於構造函數來說,是一個屬性,對於生成的對象來說,是一個原型對象。prototype的作用是讓構造函數生成的對象共享方法和屬性,彌補構造函數的缺點。例子說明:
function Persion() {
this.name='陳志豪';
this.say=function () {
return "hi";
}
}
var man=new Persion();
var woman=new Persion();
woman.name="Kate";
Persion.prototype.ask=function () {
return 'who are you ?'
}
Persion.prototype.status='good';
console.log(Object.getOwnPropertyNames(Persion))//["length", "name", "arguments", "caller", "prototype"]
console.log(Object.getOwnPropertyNames(Persion.prototype))//["constructor", "ask", "status"]
console.log(Persion.prototype)//Object {status: "good"}
console.log(Persion.prototype.prototype)//undefined
console.log(man.prototype===Persion.prototype)//false
console.log(man.prototype)//undefined ,說明prototype是構造函數的屬性,不是生成的對象的屬性
上面代碼有註釋,自己看可以發現一些原理。
Object.getOwnPropertyNames(Persion)
//看看Persion 有什麼屬性
Persion.hasOwnPropterty('ask')//Persion是否有一個屬性叫'ask',在上例中,會返回false。因爲它是Persion.prototype(原型對
象,可以理解爲Java父類的對象)的屬性,不是Persion的屬性的地方
(3)構造器的prototype的constructor屬性。
注意我說的是構造器的prototype的constructor屬性,不是構造器的constructor屬性,有點囉
嗦,但有必要強調一下
function Persion() {
this.name='陳志豪';
}
var girl=new Persion.prototype.constructor()
console.log(Persion.prototype.constructor)//function Persion() {this.name='陳志豪';}
console.log(girl.constructor)//function Persion() {this.name='陳志豪';}
console.log(Persion.constructor)//function Function() { [native code] }
//利用Persion.prototype.constructor或者girl.constructor才能正確的創建對象,
// Persion.constructor不行
(4)instanceof 運算符,判斷是否某個構造器生成的對象,返回布爾值。
注意用instanceof 判斷是否原型,或者原型的原型 ... ... 的實例對象,也會返回true
function Persion() {
this.name='陳志豪';
}
var girl=new Persion.prototype.constructor()
var boy=new Persion()
console.log(girl instanceof Persion)//true
console.log(boy instanceof Persion)//true
console.log(girl instanceof Object)//true