繁体   English   中英

使用父实例在父对象中调用子方法类

[英]Call child method class in parent with parent instance

我不希望我的父类太长,所以我从中分离一些方法并创建子类。

但是我不想将子类用作实例,但希望仅由父类使用。

class Parent {
  parentMethod() {
    this.foo(); // execute from parent
  }
}

class Child extends Parent {
  foo() {
    console.log('foo!');
  }
}

const parent = new Parent();
parent.parentMethod(); // execute parent method which execute child method

原因:

未捕获的TypeError:this.foo不是函数

我不希望我的父类太长,所以我从中分离了一些方法

好。

因此,我创建了子类,但是我不想将子类用作实例。

不,在这里子类化是错误的方法。 特别是如果您不想实例化子类,它甚至不是解决问题的方法。

要分离代码单元,请将它们分解为单独的函数。 那些不需要通过继承链接到调用者,也完全不需要是类的方法。 写吧

class MyClass {
  myMethod() {
    foo();
  }
}

function foo() {
  console.log('foo!');
}

const instance = new MyClass();
instance.myMethod();

或由多个较小的助手组成您的对象:

class Outer {
  constructor() {
    this.helper = new Inner();
  }
  myMethod() {
    this.helper.foo();
  }
}

class Inner {
  foo() {
    console.log('foo!');
  }
}

const instance = new Outer();
instance.myMethod();

如果要在子类Child类中使用Parent类,则需要执行以下操作:

class Parent {
    foo() {
        console.log('foo!');
    }
}


class Child extends Parent {
    constructor() {
        super();
    }
}

let c = new Child(); //instantiate Child class
c.foo(); // here you are calling super.foo(); which is the Parent classes method for foo.
//foo!

super关键字用于访问和调用对象父对象上的函数。

如何使用超级

或者,或者,如果您希望在包装foo父方法的子类上创建一个方法,而不是通过在子构造函数中调用super来实例化父类来访问它:

class Parent {
    foo() {
        console.log('foo!');
    }
}


class Child extends Parent {
    method() {
        this.foo();
    }
}

let c = new Child();
c.method();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM