2

I have a class for basic stuff and I use it to extends in another classes, what I want to do is exec some code in a function with the same name in my class and then exec the parent class function.

Here are an example:

class A {
  foo() {
    // Do something
  }
}

class B extends A {
  foo() {
    // Do something different from A
    // Now exec the parent foo()
  }
}
0

2 Answers 2

3

you can use super:

class A {
  foo() {
    console.log('A')
  }
}

class B extends A {
  foo() {
    console.log('B')
    super.foo()
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Your answer is correct, but I think we should avoid use super, if method is overloaded, because it can be confusing.
It works really well, it's exactly what I have to do, there is a way to do it without super? @PiotrBiałek
@MateusKoppe My solution above does it withour super, there's more code, but I think it's a better practice.
Yes, I agree, but the problem isn't the quantity of code but the name of the function.
1

If you want to do something diffrent and don't repeat yourself you can do it in this way:

class A {
  foo() {
    // Do something
  }
}

class B extends A {
  baz() {
    this.bar();
    this.foo();
  }

  bar() {
    // Do something different from A
  }
}

3 Comments

It works, but I have use the same name as the parent function
So you can do it in way as wrote @Doron, but as I wrote I think we should avoid use super, if method is overloaded, because it can be confusing
I understand your point, thanks! I will think about it in the next times that I have to use it. But in this case the answer from @Doron was exactly what I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.