object literal方式創(chuàng)建對(duì)象
- 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.
-
Employee
是個(gè)函數(shù) - 根據(jù)上面的文字跟chrome輸出,可以看出
Employee.prototype
是 object,并有一個(gè)construct function就是其本身 -
Employee.__proto__
為function() {}
prototype based inheritance
Object.create()
-
Manager.prototype
只是一個(gè)原型為Employee.prototype
的object
一個(gè)中間過渡的func F
關(guān)于以上兩種方式的繼承:
-
使用第二種
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.prototype
為 A.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 . . .]