目录
class与ES5构造函数原型模式创建函数
ES5构造函数原型模式创建函数
创建一个人类 name,age,height run方法
function People(name,age,height){
this.name=name
this.age=age
this.height=height
}
People.prototype.run=function(){
console.log("正在跑")
}
let p1=new People("王一",21,193)
ES5构造函数原型模式创建函数的继承
function Student(name,age) {}
Student.prototype = new Person("小杨", "18","180")
var s1 = new Student("xiaoyang", "21","180")//不执行
s1.eat()//可以执行
console.log(s1);//得到的是 小杨 18 180
ES6class 创建
class People{
//构造函数
constructor(name,age,height){
this.name=name
this.age=age
this.height=height
}
run(){
console.log("正在跑")
}
}
let p1=new People("王一",21,193)
let p2=new People("王二",22,187)
console.log(p1.run===p2.run) //true
ES6 class创建类 的继承
//继承一个学生类
class Student extends People{
constructor(name,age,height,score){
//super()方法 父级的构造函数
super(name,age,height)
//super必须写在 自己属性的上方
this.score=score
}
showInfo(){
console.log(this.name)
}
run(){
console.log(this.name+"正在跑")
}
}
let s1=new Student("王一",21,22,65)
console.log(s1 instanceof Student)
console.log(s1)
二者对比 :
1、ES5中 需要将属性写在构造函数中 构造函数做了模拟类的做用
方法写在构造函数的原型对象中
ES6中 直接将属性写在对应的class类中的constructor中 方法直接通过方法名加函数写在类中
代码简洁 方便书写
2、ES5中 继承需要结合原型和构造函数一起来继承 代码繁琐
ES6中 可以直接子类通过extends继承父类的所有方法和属性
通过super()方法 写父级的构造函数(需写在自己属性的上方)
子类自己的属性也可以直接通过方法名加函数写在子类中
如需修改父类的方法 直接同名方法覆盖即可