Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript重写子类最佳实践中的父类函数_Javascript_Class_Inheritance_Ecmascript 6 - Fatal编程技术网

Javascript重写子类最佳实践中的父类函数

Javascript重写子类最佳实践中的父类函数,javascript,class,inheritance,ecmascript-6,Javascript,Class,Inheritance,Ecmascript 6,我有一个父基类,它设置了一些在子类中使用的常用函数,如下所示: class BaseClass() { constructor(someValue){ this.value = value } methodToBeOverridden(){ //This is implemented in the child class. } } 我想知道在像上面这样的子类中被重写的方法的常见做法是什么。目前,我只留下一条评论,里面什么都没有。

我有一个父基类,它设置了一些在子类中使用的常用函数,如下所示:

class BaseClass() {

    constructor(someValue){
        this.value = value
    }
    methodToBeOverridden(){
        //This is implemented in the child class.
    }
}

我想知道在像上面这样的子类中被重写的方法的常见做法是什么。目前,我只留下一条评论,里面什么都没有。有更好的方法吗?

如果您打算在继承
基类的类中实现
methodtobeoverrided()
,可以加入父类

methodToBeOverridden() {
    throw new Error('This method needs to be implemented!');
}
但实际上,我不确定我是否看到了这一点-如果您只是不在
BaseClass
中定义
methodtobeoverrided()
并在某个子实例上调用它,那么由于该方法未定义,将抛出一个错误


TypeScript的概念是,它更适合解决您的问题

abstract class BaseClass {
    constructor(public value: any) {
      //
    }

    abstract methodToBeOverridden(): void;
}

因此,按照上面的方法,如果子类不重写该方法,则会抛出错误?您所说的是正确的,但要绝对清楚,它仅在对未实现该方法的子类调用
methodtobeoverrided()
时抛出。