Javascript 对象继承(1)

728 查看

object literal方式创建对象



![ object literal 方式创建的对象]

object literal chrome 输出
  • b 是一个以 Object.prototype 为原型的对象
  • 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是个函数
  • 根据上面的文字跟chrome输出,可以看出Employee.prototype是 object,并有一个construct function就是其本身
  • Employee.__proto__function() {}

prototype based inheritance

Object.create()


Object.create inherit.png

Object.create inheite chrome.png
  • Manager.prototype 只是一个原型为Employee.prototype的object

一个中间过渡的func F


F() inherit.png

F() inherit chrome.png

关于以上两种方式的继承:


为什么使用中间函数F实现继承.png

为什么使用中间函数F实现继承 chrome.png
  • 使用第二种B.prototype = new A();方式,会报上图的错误,你需要改成B.prototype = new A("");的方式,比较繁琐
  • 使用第一种 B.prototype = new F();的方式继承 ,不会出现上图中的错误,可以把它封装成函数,方便使用

Javascript的坑

可以看上面第二种方式 B.prototype.constructor = B;, 看到这句刚开始有点不理解:
我的想法是, F.prototype = A.prototype; B.prototype = new F(); ,这句让 B.prototypeA.prototype原型的一个对象,而一个A.prototype原型的对象,继承成了一个construct function的方法,那使用 B.prototype.constructor = B; 不是把 prototype chain 上的construct function 给修改了吗?
其实不是的。

从下面代码可以看出,从javascript对象取属性值时,会一次从prototype chain上找。但是给一个新属性赋值时,直接在本对象添加,而不是更改prototype chain上的值
![Uploading aa 跟 aa.proto同名属性 chrome_074940.png . . .]


aa 跟 aa.proto同名属性.png

aa 跟 aa.proto同名属性 chrome.png