浅谈javascript中的constructor属性。

来源:互联网 发布:slax linux初始密码 编辑:程序博客网 时间:2024/05/19 04:26

我认为只有对象的__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对象。

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

原创粉丝点击