JS问题整理与思考--es6中Class和普通构造函数有何区别。

原型语法

function MathHandler(x, y) {
    this.x = x
    this.y = y
}
MathHandler.prototype.add = function () {
    return this.x + this.y
}
var m = new MathHandler(1, 2);
console.log(m.add())

class 语法

class MathHandle {
    constructor(x,y){
        this.x = x
        this.y = y
    }
    add() {
        return this.x + this.y
    }
}
const m = new MathHandler(1, 2);
console.log(m.add())

语法糖

// typeof MathHandler  // function
// MathHandler.prototype.constructor === MathHandler   // true
// m.__proto__ === MathHandler.prototype   // true

继承

// 动物
function Animal() {
    this.eat = function () {
        console.log('Animal eat')
    }
}
// 狗
function Dog() {
    this.bark = function () {
        console.log('Dog Bark')
    }
}
Dog.prototype = new Animal();
// 哈士奇
var hashiqi  = new Dog()
hashiqi.bark()
hashiqi.eat()

// ------------

class Animal {
    constructor (name){
        this.name = name
    }
    eat(){
        console.log(111)
    }
}
class Dog extends Animal{
    constructor (name){
        super(name)
        this.name = name
    }
    say(){
        console.llg(222)
    }

}
const dog  = new Dog('heshiqi')
dog.say()
dog.eat()
  • Class在语法上更贴合面向对象都写法
  • Class实现继承更加易读/易理解
  • 更易于写java等后端语言等使用
  • 本质还是语法糖,使用prototype

随机浏览