国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript對(duì)象創(chuàng)建及繼承原理實(shí)例解剖

2024-05-06 14:19:31
字體:
供稿:網(wǎng)友
對(duì)象創(chuàng)建:
當(dāng)一個(gè)函數(shù)對(duì)象被創(chuàng)建時(shí)候,F(xiàn)unction構(gòu)造器產(chǎn)生的函數(shù)對(duì)象會(huì)運(yùn)行類似這樣的代碼:
代碼如下:
this.prototype={constructor:this};

假設(shè)函數(shù)F
F用new方式構(gòu)造對(duì)象時(shí),對(duì)象的constructor被設(shè)置成這個(gè)F.prototype.constructor
如果函數(shù)在創(chuàng)建對(duì)象前修改了函數(shù)的prototype,會(huì)影響創(chuàng)建出來對(duì)象的construtor屬性
如:
代碼如下:
function F(){};
F.prototype={constructor:'1111'};
var o=new F();//o.constructor===‘1111' true

繼承原理:
JavaScript中的繼承是使用原型鏈的機(jī)制,每個(gè)函數(shù)的實(shí)例都共享構(gòu)造函數(shù)prototype屬性中定義的數(shù)據(jù),要使一個(gè)類繼承另一個(gè),需要把父函數(shù)實(shí)例賦值到子函數(shù)的prototype屬性。并且在每次new實(shí)例對(duì)象時(shí),對(duì)象的私有屬性__proto__會(huì)被自動(dòng)連接到構(gòu)造函數(shù)的prototype。
instanceof就是查找實(shí)例對(duì)象的私有prototype屬性鏈來確定是否是指定對(duì)象的實(shí)例
具體實(shí)例:
代碼如下:
//instanceof實(shí)現(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 自動(dòng)完成
TreeView.prototype.constructor=TreeView;//修正constructor
var view=new TreeView();//view.__proto__=TreeView.prototype 自動(dòng)完成
alert(view instanceof View); //true 查找到view.__proto__.__proto__時(shí)找到
alert(view instanceof TreeView); //true 查找到view.__proto__時(shí)找到
alert(Myinstanceof(view,View)); //true
alert(Myinstanceof(view,TreeView)); //true

上面自定義的Myinstanceof就是自己實(shí)現(xiàn)的一個(gè)instanceof功能的函數(shù),由于IE內(nèi)核實(shí)例存儲(chǔ)prototype不是__proto__,所以Myinstanceof會(huì)無法通過,其他瀏覽器上應(yīng)該都沒有問題
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 富民县| 华蓥市| 临猗县| 湟中县| 凤台县| 宜都市| 德庆县| 洛阳市| 清涧县| 平安县| 鄂伦春自治旗| 商水县| 武穴市| 长岛县| 武清区| 南投县| 太仆寺旗| 洞口县| 什邡市| 连江县| 荆门市| 合肥市| 木兰县| 敦煌市| 汤阴县| 弋阳县| 瓮安县| 于田县| 林周县| 宣城市| 龙游县| 溆浦县| 大厂| 浙江省| 同江市| 额尔古纳市| 枝江市| 大宁县| 嘉禾县| 宝丰县| 灵台县|