JS - 如何使用js模拟抽象类

152 阅读1分钟

1、使用构造函数和原型链

通过在构造函数中抛出错误来确保抽象方法在子类中被实现

//抽象类
function AbstractClass() {
    if (this.constructor === AbstractClass) {
        throw new Error("abstract class cannot instanced")
    }
}

AbstractClass.prototype.abstractMethod = function() {
    throw new Error('abstract method must be by subclass')
}

//子类
function SubClass() {
    AbstractClass.call(this)
}

SubClass.prototype = Object.create(AbstractClass.prototype)
SubClass.prototype.constructor = SubClass

SubClass.prototype.abstractMethod = function() {
    console.log("implement abstract method in SunClass")
}

// 测试
try {
    const instance = new AbstractClass() // 抛出错误
} catch(e) {
    console.error(e.message)
}

2、使用es6 class类

es6提供了更现在的语法,可以更清晰地模拟抽象类和金泰方法

// 抽象类
class AbstractClass {
    constructor(){
        if (this.constructor === AbstractorClass) {
            throw new Error("abstract class cannot instanced")
        }
    }
    
    abstractMethod(){
        throw new Error('Abstract method must be implemented')
    }
}

//子类
class SubClass extends AbstractClass {
    abstractMethod(){
        console.log('implement abstract method in SunClass')
    }
}

//测试
try {
    const instance = new AbstractClass()
} catch(e) {
    console.log(e.message)
}