1、向原型鏈上添加屬性為什么用prototype,而一般不用__proto__
2、javascript為什么要設(shè)置一個(gè)函數(shù)對(duì)象,他的作用是什么
3、更深層次了解原型鏈
如下兩段代碼,分別是使用對(duì)象字面量和構(gòu)造函數(shù)創(chuàng)建對(duì)象。
代碼段1:
var a={"name":"nihao"}; console.log(a);
代碼段2:
var a=function(name){ this.name=name; }; var b= new a("nihao"); console.log(b);
首先,我們需要知道:
1、函數(shù)對(duì)象的原型是對(duì)象(原型鏈為:實(shí)例,通過(guò)new構(gòu)造函數(shù)-->函數(shù)對(duì)象-->對(duì)象-->null)
2、函數(shù)有prototype屬性,而對(duì)象沒(méi)有
然后,在某些場(chǎng)景下,我們有一個(gè)公共的屬性,需要多個(gè)新建的對(duì)象去繼承,這個(gè)時(shí)候就能體現(xiàn)出函數(shù)對(duì)象的特點(diǎn)了,我們看下代碼:
1、使用構(gòu)造器
var a=function(name){ this.name=name; }; a.prototype.sex="nan"; var b= new a("nihao"); console.log(b); console.log(b.name); console.log(b.sex); var c=new a("test"); console.log(c); console.log(c.name); console.log(c.sex);
如上,可以很容易的實(shí)現(xiàn)屬性或方法的繼承,在控制臺(tái)打印上述代碼,可以很容易看到原型鏈?zhǔn)沁@樣的(以對(duì)象b為例):對(duì)象b-->函數(shù)對(duì)象-->對(duì)象-->null
2、使用對(duì)象字面量
使用對(duì)象字面量創(chuàng)建的是對(duì)象,他沒(méi)有prototype屬性,所以我們只能通過(guò)__proto__,但是在對(duì)象上使用__proto__可能會(huì)導(dǎo)致一些問(wèn)題的出現(xiàn)。代碼如下:
var a={"name":"nihao"}; a.__proto__.sex="nan"; console.log(a); console.log(a.name); console.log(a.sex); var b={}; console.log(b); console.log(b.name); console.log(b.sex);
如上,運(yùn)行上面代碼,可以很容易得到運(yùn)行結(jié)果:
{name: "nihao"} nihao nan {} undefined nan
哎,這個(gè)就很奇怪了,b對(duì)象明明設(shè)置的為空啊?這是因?yàn)樵趫?zhí)行a.__proto__.sex="nan";時(shí)候,程序向?qū)ο蟮脑蜕咸砑恿艘粋(gè)屬性sex,而b是對(duì)象也是繼承的對(duì)象的原型,多以導(dǎo)致了這個(gè)問(wèn)題的出現(xiàn)。
最后,總結(jié)下來(lái)就是:
函數(shù)對(duì)象是繼承自對(duì)象的原型,有了函數(shù)對(duì)象,我們可以給函數(shù)的原型添加屬性,這些屬性保存在函數(shù)對(duì)象中,但是又不會(huì)影響其他對(duì)象。
相關(guān)推薦:
淺談js之字面量、對(duì)象字面量的訪問(wèn)、關(guān)鍵字in的用法
Javascript中對(duì)這兩種對(duì)象字面量(json)的操作方式有何不同?
Javascript 中 class、構(gòu)造函數(shù)、工廠函數(shù)詳解
以上就是對(duì)象字面量和構(gòu)造函數(shù)創(chuàng)建對(duì)象詳解的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!