浅谈javascript中的constructor属性。

我认为只有对象的__proto__属性才具有constructor属性。对象本身没有constructor属性,然后去

它的__proto__属性中寻找constructor属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<! 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对象。

如果有什么错误的地方,希望有大牛能指点一二!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值