Class与构造函数的区别?

65 阅读1分钟

一、js构造函数

function createPerson(name,age,sex){
    this.name=name
    this.age=age
    this.sex=sex
}
createPerson.prototype.sayName=function (){
    console.log('我的名字是'+this.name)
}
const per=new createPerson('zhangsan',18,'女')
per.sayName()

二、class类

class createPerson{
    constructor(name,age,sex){
        this.name=name
        this.age=age
        this.sex=sex
    }
    sayName(){
        console.log('我的名字是'+this.name)
    }
}
const per=new createPerson('zhangsan',18,'女')
per.sayName()

三、语法糖

将上面两段代码加入如下代码运行,结果一致。

console.log(typeof createPerson) //function
console.log(createPerson.prototype.constructor===createPerson)//true
console.log(per.__proto__===createPerson.prototype)//true

class类相当于构造函数的语法糖

四、继承

1.使用构造函数实现继承

function Aniamal(){
    this.eat=function(){
        console.log("Aniamal eat")
    }
}
function Dog(){
    this.bark=function(){
        console.log("Dog bark")
    }
}
Dog.prototype=new Aniamal()

const hashiqi=new Dog()
hashiqi.bark()
hashiqi.eat()

2. class类继承

class Aniamal{
    constructor(name){
        this.name=name
    }
    eat(){
        console.log(this.name+"eat")
    }
}

class Dog extends Aniamal{
    constructor(name){
        super(name)//super就是被继承的对象的constrctor
    }
    bark(){
        console.log(this.name+"bark")
    }
}

const hashiqi=new Dog('拉布拉多')
hashiqi.bark()
hashiqi.eat()

1、子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
2、ES5的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6的继承机制完全不同,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。

五、总结

  • 构造函数与class类无本质差别,只是前者是es5写法,后者是es6写法。
  • class语法上更贴近面向对象写法。
  • class实现继承更加易读易理解。