js 原型对象

js 原型对象

每个对象都有一个原型对象,我们这里用构造函数来举例

创建一个构造函数

          function Dog(name,age,sex,type) {
    
    
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.type = type;
        }
        //调用构造函数=>对象实例化
            let white = new Dog("小白",1,"女","拉布拉多")
            console.log(white);
返回的结果是

在这里插入图片描述

这里打开__proto__可以看到其中的constructor是我们的构造函数

我们在实例化一个对象,并给设置一个关系

        function Dog(name, age, sex, type) {
    
    
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.type = type;
        }
        Dog.prototype.relation = "lover"
        let white = new Dog("小白", 1, "女", "拉布拉多")
        let blue = new Dog("小陈", 2, "男", "萨摩耶")
        console.log(white);
        console.log(white.relation);
        console.log(blue);

下面是运行结果

在这里插入图片描述

我们通过这个结果可以看的出 我们实例化对象的时候是可以得到他的relation值的,因此他们应该是指向同一个原型对象的,所以我们也是可以调用的出他们的constructor属性 也就是他们的构造函数

      function Dog(name, age, sex, type) {
    
    
            this.name = name;
            this.age = age;
            this.sex = sex;
            this.type = type;
        }
        Dog.prototype.relation = "lover"
        let white = new Dog("小白", 1, "女", "拉布拉多")
        let blue = new Dog("小陈", 2, "男", "萨摩耶")
        console.log(white);
        console.log(white.relation);
        console.log(blue);
        console.log(white.constructor);

在这里插入图片描述

所以我们可以得出 我们的实例化对象的constructor可以指向构造函数,而构造函数的的prototype指向一个原型对象而实例化对象的__proto__也指向我们的原型对象

再送大家一张图片有助理解

再送大家一张图片有助理解

猜你喜欢

转载自blog.csdn.net/EWJRQKJRQ/article/details/108329258
今日推荐