一.通过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)进行查找。