亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript中創(chuàng)建對象和繼承示例解讀

 更新時間:2014年02月12日 15:26:12   作者:  
這篇文章主要介紹了JavaScript中怎樣創(chuàng)建對象和繼承,需要的朋友可以參考下
對象創(chuàng)建:

當(dāng)一個函數(shù)對象被創(chuàng)建時候,F(xiàn)unction構(gòu)造器產(chǎn)生的函數(shù)對象會運(yùn)行類似這樣的代碼:
復(fù)制代碼 代碼如下:

this.prototype={constructor:this};

假設(shè)函數(shù)F
F用new方式構(gòu)造對象時,對象的constructor被設(shè)置成這個F.prototype.constructor
如果函數(shù)在創(chuàng)建對象前修改了函數(shù)的prototype,會影響創(chuàng)建出來對象的construtor屬性

如:
復(fù)制代碼 代碼如下:

function F(){};
F.prototype={constructor:'1111'};
var o=new F();//o.constructor===‘1111' true

繼承原理:

JavaScript中的繼承是使用原型鏈的機(jī)制,每個函數(shù)的實例都共享構(gòu)造函數(shù)prototype屬性中定義的數(shù)據(jù),要使一個類繼承另一個,需要把父函數(shù)實例賦值到子函數(shù)的prototype屬性。并且在每次new實例對象時,對象的私有屬性__proto__會被自動連接到構(gòu)造函數(shù)的prototype。

instanceof就是查找實例對象的私有prototype屬性鏈來確定是否是指定對象的實例

具體實例:
復(fù)制代碼 代碼如下:

//instanceof實現(xiàn)
function Myinstanceof(obj,type)
{
var proto=obj.__proto__;
while(proto)
{
if(proto ===type.prototype)break;
proto=proto.__proto__;
}
return proto!=null;
}


function View(){}
function TreeView(){}
TreeView.prototype=new View();//TreeView.prototype.__proto__=TreeView.prototype 自動完成
TreeView.prototype.constructor=TreeView;//修正constructor
var view=new TreeView();//view.__proto__=TreeView.prototype 自動完成
alert(view instanceof View); //true 查找到view.__proto__.__proto__時找到
alert(view instanceof TreeView); //true 查找到view.__proto__時找到
alert(Myinstanceof(view,View)); //true
alert(Myinstanceof(view,TreeView)); //true

相關(guān)文章

最新評論