最近阅读某本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