浅谈javascript中的constructor属性。
最近阅读某本javascript指南书时,发现书中强调的对象都具有constructor属性,我觉得这有点不对。
我认为只有对象的__proto__属性才具有constructor属性。对象本身没有constructor属性,然后去
它的__proto__属性中寻找constructor属性。
<!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对象中的属性,并不是每个对象中的属性。

上图就是tri对象。
如果有什么错误的地方,希望有大牛能指点一二!
生命不息,撸码不止

浙公网安备 33010602011771号