Javascript 對(duì)象繼承(1)

object literal方式創(chuàng)建對(duì)象

![ object literal 方式創(chuàng)建的對(duì)象]
object literal chrome 輸出
  • b 是一個(gè)以 Object.prototype 為原型的對(duì)象
  • b.__proto__ 指向的是 Object.prototype

原型繼承

construct function

every JavaScript function (except functions returned by the ECMAScript 5 Function.bind() method) automatically has a prototype property. The value of this property is an object that has a single nonenumerable constructor property. The value of the constructor property is the function object.
---David Flanagan. “JavaScript: The Definitive Guide.” iBooks.

construct function.png
construct function chrome.png
  • Employee是個(gè)函數(shù)
  • 根據(jù)上面的文字跟chrome輸出,可以看出Employee.prototype是 object,并有一個(gè)construct function就是其本身
  • Employee.__proto__function() {}

prototype based inheritance

Object.create()

Object.create inherit.png
Object.create inheite chrome.png
  • Manager.prototype 只是一個(gè)原型為Employee.prototype的object

一個(gè)中間過渡的func F

F() inherit.png
F() inherit chrome.png

關(guān)于以上兩種方式的繼承:

為什么使用中間函數(shù)F實(shí)現(xiàn)繼承.png
為什么使用中間函數(shù)F實(shí)現(xiàn)繼承 chrome.png
  • 使用第二種B.prototype = new A();方式,會(huì)報(bào)上圖的錯(cuò)誤,你需要改成B.prototype = new A("");的方式,比較繁瑣
  • **使用第一種 B.prototype = new F();的方式繼承 **,不會(huì)出現(xiàn)上圖中的錯(cuò)誤,可以把它封裝成函數(shù),方便使用

Javascript的坑

可以看上面第二種方式 B.prototype.constructor = B;, 看到這句剛開始有點(diǎn)不理解:
我的想法是, F.prototype = A.prototype; B.prototype = new F(); ,這句讓 B.prototypeA.prototype原型的一個(gè)對(duì)象,而一個(gè)A.prototype原型的對(duì)象,繼承成了一個(gè)construct function的方法,那使用 B.prototype.constructor = B; 不是把 prototype chain 上的construct function 給修改了嗎?
其實(shí)不是的。

從下面代碼可以看出,從javascript對(duì)象取屬性值時(shí),會(huì)一次從prototype chain上找。但是給一個(gè)新屬性賦值時(shí),直接在本對(duì)象添加,而不是更改prototype chain上的值
![Uploading aa 跟 aa.proto同名屬性 chrome_074940.png . . .]

aa 跟 aa.__proto__同名屬性.png

aa 跟 aa.__proto__同名屬性 chrome.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • You Don't Know JS: this & Object Prototypes Chapter 5: Pr...
    大橙子CZ閱讀 607評(píng)論 0 2
  • 只賣同城 人民廣場(chǎng)大廟附近 自提 最低價(jià) 不刀 浪費(fèi)時(shí)間 喜歡的聯(lián)系
    loveuyeah閱讀 161評(píng)論 0 1
  • 《夢(mèng)臺(tái)》 鏡花臨媚掩紅妝,風(fēng)月殘局落醉殤。 幽影余癡妃子夢(mèng),三音堪酒余思腸。 《屏臺(tái)》 珠簾霓曲夢(mèng)方醒,樓鳳錯(cuò)眉蘭...
    景黎閱讀 297評(píng)論 2 11
  • 每天下班大部分時(shí)間會(huì)選擇走路回來,勞累了一天,不想在熙熙攘攘的人群中騎著自行車風(fēng)風(fēng)火火擠出一條道。途中有一...
    Iria瑩閱讀 420評(píng)論 0 0