javascript中的class

ES5 定义构造函数

通过构造函数加属性,通过原型加方法:

function MathHandle(x, y) {
    this.x = x;
    this.y = y;
}

MathHandle.prototype.add = function() {
    return this.x + this.y;
}

var m = new MathHandle(1, 2);
console.log(m.add());   // 3

ES6 Class语法

class MathHandle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
        
    add() {
        return this.x + this.y;
    }
}

var m = new MathHandle(1, 2);
console.log(m.add());   // 3

class 实际上是语法糖,编译后就是ES5中的构造函数:

typeof MathHandle;  // function
MathHandle === MathHandle.prototype.constructor;    // true
m.__proto__ === MathHandle.prototype  // true

实例的隐式原型 = 构造函数的显式原型

ES5 继承

将低级构造函数的原型赋值为高级构造函数的实例来实现继承:

// 动物
function Animal() {
    this.eat = function () {
        alert('Animal eat')
    }
}

// 狗
function Dog() {
    this.bark = function () {
        alert('Dog bark')
    }
}

// 绑定原型,实现继承
Dog.prototype = new Animal()

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

ES6 class 继承

通过 extends 关键字和 super 方法实现继承:

class Animal {
    constructor(name) {
        this.name = name;
    }
    eat() {
        console.log(`${this.name} eat`);
    }
}

class Dog extends Animal {
    constructor(name) {
        super(name);
        this.name = name;
    }
    say() {
         console.log(`${this.name} say`);
    }
}

const hashiqi = new Dog("哈士奇");
hashiqi.eat();
hashiqi.say();

本质还是语法糖,使用 prototype。

你可能感兴趣的:(javascript中的class)