構(gòu)造函數(shù)
使自己的對(duì)象多次復(fù)制,同時(shí)實(shí)例根據(jù)設(shè)置的訪問等級(jí)可以訪問其內(nèi)部的屬性和方法
當(dāng)對(duì)象被實(shí)例化后星岗,構(gòu)造函數(shù)會(huì)立即執(zhí)行它所包含的任何代碼
functionmyObject(msg){
特權(quán)屬性(公有屬性)
this.myMsg?=?msg;//只在被實(shí)例化后的實(shí)例中可調(diào)用
this.address?=?'上海';
私有屬性
varname?=?'豪情';
varage?=?29;
varthat?=this;
私有方法
functionsayName(){
alert(that.name);
}
特權(quán)方法(公有方法)
能被外部公開訪問
這個(gè)方法每次實(shí)例化都要重新構(gòu)造而prototype是原型共享沥匈,所有實(shí)例化后设褐,都共同引用同一個(gè)
this.sayAge?=function(){
alert(name);//在公有方法中可以訪問私有成員
}
私有和特權(quán)成員在函數(shù)的內(nèi)部倡缠,在構(gòu)造函數(shù)創(chuàng)建的每個(gè)實(shí)例中都會(huì)包含同樣的私有和特權(quán)成員的副本牵啦,
因而實(shí)例越多占用的內(nèi)存越多
}
公有方法
適用于通過new關(guān)鍵字實(shí)例化的該對(duì)象的每個(gè)實(shí)例
向prototype中添加成員將會(huì)把新方法添加到構(gòu)造函數(shù)的底層中去
myObject.prototype.sayHello?=function(){
alert('hello?everyone!');
}
靜態(tài)屬性
適用于對(duì)象的特殊實(shí)例寇僧,就是作為Function對(duì)象實(shí)例的構(gòu)造函數(shù)本身
myObject.name?=?'china';
靜態(tài)方法
myObject.alertname?=function(){
alert(this.name);
}
實(shí)例化
varm1?=newmyObject('111');
----?測試屬性?----
console.log(myObject.name);?//china
console.log(m1.name);?//undefined,?靜態(tài)屬性不適用于一般實(shí)例
console.log(m1.constructor.name);?//china,?想訪問類的靜態(tài)屬性摊腋,先訪問該實(shí)例的構(gòu)造函數(shù),然后在訪問該類靜態(tài)屬性
console.log(myObject.address);?//undefined,?myObject中的this指的不是函數(shù)本身嘁傀,而是調(diào)用address的對(duì)象兴蒸,而且只能是對(duì)象
console.log(m1.address);?//上海?此時(shí)this指的是實(shí)例化后的m1
----?測試方法?----
myObject.alertname();?//china,直接調(diào)用函數(shù)的類方法
m1.alertname();?//FF:?m1.alertname?is?not?a?function,?alertname?是myObject類的方法,和實(shí)例對(duì)象沒有直接關(guān)系
m1.constructor.alertname();?//china,?調(diào)用該對(duì)象構(gòu)造函數(shù)(類函數(shù))的方法(函數(shù))
m1.sayHello();?//hello?everyone,?myObject類的prototype原型下的方法將會(huì)被實(shí)例繼承
myObject.sayHello();?//myObject.sayHello?is?not?a?function细办,sayHello是原型方法橙凳,不是類的方法
----?測試prototype?----
console.log(m1.prototype);?//undefined,?實(shí)例對(duì)象沒有prototype
console.log(myObject.prototype);?//Object
alert(myObject.prototype.constructor);?//console.log返回myObject(msg),此時(shí)alert()更清楚笑撞,相當(dāng)于myObject
console.log(myObject.prototype.constructor.name);?//china,?相當(dāng)于myObject.name;