什么是对象原型,什么是原型对象,什么是constructor,什么是原型链,详细解析

原型对象 : prototype

概念:原型对象是构造函数上的一个属性,用来创建公共的方法

原型对象怎么使用? 如何使用原型对象设置公共方法?

//语法: 构造函数.prototype.方法名 = function() {}

      function Student(uname) {

        this.uname = uname

      }

      // 设置公共方法

      Student.prototype.eat = function () {

        console.log('吃饭')

      }

      let zs = new Student('张三')

      let ls = new Student('李四')

      console.log(zs.eat === ls.eat)    // true

对象原型 __proto__

概念: 对象原型是实例对象(对象)身上的一个属性, 该属性叫 __proto__ (注意: 在谷歌浏览器中 [[prototype]] )

 function Student(uname) {

            this.uname = uname;

        }

        //设置公共方法

        Student.prototype.eat = function() {

            console.log('吃饭');

        }

        //通过构造函数创建了一个zs 实例对象

        let zs = new Student('张三');

        zs.eat();

        // console.log(zs.__proto__);

        // 验证: 对象原型 指向  原型对象

        console.log(zs.__proto__ === Student.prototype);

  对象原型有什么作用?

   作用: 对象原型(__proto__) 默认指向了 原型对象(prototype),导致 实例对象可以调用公共方法

   __proto__ 就是实例对象和原型对象之间的一个桥梁

 constructor  

概念:是原型对象(prototype) 和 对象原型(__proto__)身上的一个属性

作用: constructor会记录当前对象属于哪个构造函数 

代码演示:

function Student(uname) {

        this.uname = uname

      }

      // 公共方法

      Student.prototype.eat = function () {

        console.log('吃饭')

      }

      console.log('原型对象', Student.prototype)

      let zs = new Student('张三')

      console.log('对象原型', zs.__proto__)

        // 输出:

 

原型链

概念 : 方法的查找规则 ---> 沿着原型链向上一级查找 (就近原则)

 function Student(age) {

        this.age = age

      }

      let zs = new Student(23)

      zs.age.toStest()

       console.dir(Object);

       zs.age.toString();

       当前原型对象身上没有   toString() 方法

       当前对象身上也么有设置 toString() 方法

       为什么可以调用?

       原因: 由于原型链存在

       原型链:

       1. zs 调用 toString()方法的时候,先在当前对象身上查找是否有方法

       2. zs 会沿着__proto__ 去 prototype 身上去找

       3. Object构造函数就是自定义对象中的老大

       window是DOM对象中的老大

       Object是自定义对象中的老大

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈十一i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值