简体   繁体   中英

Call child method class in parent with parent instance

I don't want my parent class to be too long so I separate some methods from it and create child class.

However I don't want to use child class as a instance I want it to be used only by parent class.

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

this cause:

Uncaught TypeError: this.foo is not a function

I don't want my parent class to be too long so I separate some methods from it

Ok.

So I create child class, however I don't want to use child class as a instance.

No, subclassing is the wrong approach here. Especially if you don't want to instantiate the subclass, it's not even a solution to your problem.

To separate units of code, factor them out into separate functions. Those don't need to be linked to the caller through inheritance, and don't need to be methods of a class at all. Just write

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

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

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

Or compose your object of multiple smaller helpers:

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

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

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

If you want to use the Parent class in the subclass, Child class, then you need to do the following:

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!

The super keyword is used to access and call functions on an object's parent.

How to use super

Or, alternatively, if you'd rather create a method on the child class that wraps the parent method of foo, rather than accessing it by instantiating the parent class via calling super in the child constructor:

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


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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