最近閱讀某本javascript指南書時,發現書中強調的對象都具備constructor屬性,我以爲這有點不對。javascript
我認爲只有對象的__proto__屬性才具備constructor屬性。對象自己沒有constructor屬性,而後去html
它的__proto__屬性中尋找constructor屬性。java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> <script> //構造方法 function Shape() { this.name='Shape'; this.getName=function(){ return this.name; } } function TwoShape() { this.name='2D Shape'; } function Triangle(side,height){ this.name='Triangle'; this.side=side; this.height=height; this.getArea=function(){ return this.side*this.height/2; } } TwoShape.prototype=new Shape(); Triangle.prototype=new TwoShape(); var tri=new Triangle(5,10); console.log(Shape.prototype===shape.__proto__); console.log(tri.__proto__.constructor); //打印的是Shape構造器 console.log(tri.constructor); </script> </html>
若是說constructor是每一個對象的屬性的話,這裏的tri.constructor就應該打印的是Triangle構造方法,但這裏打印的是Shape構造方法。tri對象沒有constructor屬性,而後去tri.__proto__(Triangle.prototype)對象中尋找,而Triangle.prototype對象又指向TwoShape的實例對象,TwoShape的實例對象(假設爲twoShape)中也沒有constructor屬性,就去twoShape.__proto__對象中尋找,而TwoShape.prototype又指向Shape的實例對象,Shape的實例對象(假設爲shape)中也沒有constructor屬性,就去shape.__proto__對象中尋找,而shape.__proto__.constructor的屬性就是Shape構造方法。因此也說明了constructor屬性只是對象的__pro__屬性(對象.__proto__)中的屬性,即構造器.prototype對象中的屬性,並非每一個對象中的屬性。ide
上圖就是tri對象。this
若是有什麼錯誤的地方,但願有大牛能指點一二!prototype