构造函数的原型

原型模式:

将所有对象共享的方法或属性,绑定在对应的构造函数的原型中

function Student(name, age) { //构造函数Student 类
        this.name = name;
        this.age = age;
        // this.eat = function () {
        //     console.log(this.name + "正在吃");
        // }
    }

构造函数的 prototype 原型

将构造函数中的eat函数写到prototype原型上

Student.prototype.eat = function () { //prototype 原型
        console.log(this.name + "正在吃");
    }
    	var stu1 = new Student("王一",21);
        stu1.eat(); //王一正在吃
        var stu2 = new Student("张三",23);
        stu2.eat(); //张三正在吃
        console.log(stu1.eat==stu2.eat); //true
    //什么内容写在原型上:共有的共享的内容写到原型上

在实例化对象中的__proto__ 等于 构造函数中的 prototype ,等于对应的原型链

function Student(name, age) {
        this.name = name;
        this.age = age;
    }
    // 构造函数的 prototype 原型
    Student.prototype.eat = function () {
        console.log(this.name + "正在吃");
    }
    var stu1 = new Student("王一", 21);
    var stu2 = new Student("张三", 23);
    // 每一个实例化的对象 都包含了一个 __proto__ == 构造函数的prototype
    stu1.__proto__.showInfo = function () { // 相当于Student.prototype.showInfo=function(){}
        console.log("名称为:" + this.name + ",年龄为:" + this.age);
    };
    stu1.showInfo();
    stu2.showInfo();
    console.log(stu2.__proto__.constructor);

__proto__原型中的 constructor 对应的是 构造函数(类)
每个对象实例都具有 constructor 属性,它指向创建该实例的构造器函数。
在这里插入图片描述
在这里插入图片描述

通过函数创建的对象,如果有公用的方法或属性,可以直接写到对应的原型中,节约内存。

构造函数中 prototype
实际对象中__proto__

原型的执行顺序:先执行构造函数,如果构造函数中没有,再找原型中是否包含。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值