原型链,Class继承

一.通过class创建一个类。

(1)定义:es6新增加了class方法,但是class只是一个语法糖他和我们平时写的构造函数本质上没有如何区别。

(2)创建一个class实例

   class Student{
      constructor(name,age){
        this.name=name
        this.age=age
      }
      eat(){
          console.log('吃大闸蟹');
      }
    }

(3) 在原型对象(prototype)上访问eat方法:

Student.prototype.eat()

 (4)实例化对象上的_proto_上进行访问        

      var a1= new Student()

      console.log(a1.__proto__.eat());

 (5) 提出一个验证: 通过_proto_访问的是同一个方法吗?

代码:

console.log(prototype.eat()==a1.__proto__.eat());
   var a1= new Student()
   console.log(Student.prototype.eat()==a1.__proto__.eat());

得出一个结论:实例化对象可以通过 __proto__ 访问挂载到原型对象(prototype)的方法

(6)原型对象可以通过 constructor 指回来class实例

   代码:

console.log(Student.prototype.constructor);

图示:

二 class类的继承

(1):通过extends实现继承,通过super关键字来使用(2)

 代码:

<script>
  class Person{
    constructor(name){
      this.name=name
    }
    eat(){
      console.log('吃大闸蟹');
    }
  }
  class Student extends Person {
    constructor(name,score){
      super(name);
      this.score=score
    }
  }
  class Teacher extends Person {
    constructor(name,subject){
      super(name);
      this.subject=subject
    }
  }
  
  var a1=new Student('张三',99)
  console.log(a1);
  var a2=new Teacher('李华','英语')
  console.log(a2);

  </script>

   解析: 把公共的名字抽离出来了放到一个Person类里面,通过extends实现继承,通过super关键字来实现使用。

三.  原型链

(1)代码:

  class Person{
    constructor(name){
      this.name=name
    }
    eat(){
      console.log('吃大闸蟹');
    }
  }
  class Student extends Person {
    constructor(name,score){
      super(name);
      this.score=score
    }
  }

  
var a1=new Student('张三',99)
console.log(a1.eat());

(2)实例化对象a1上访问了eat()方法

(3)形成了三角的关系

 

 得出结论: 原型链的查找规则,现在自己的类里面进行寻找,如果找不到就会通过_proto_ 向上级的原型对象(prototype)进行查找。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值