0

I have a class like this:

class X extends Y {
  public save() {

  }
}

abstract class Y {
  public saving() {

  }
}

const x = new X;
x.save();

How can I make sure each call to save triggers saving before?

In PHP, we can use __call and check the method name. Is there any similar approach with Javascript?

Igor Milla
  • 2,767
  • 4
  • 36
  • 44
Aris
  • 2,978
  • 5
  • 22
  • 31
  • Is that a JavaScript code? `abstract` is a reserved keyword in JavaScript as mentioned [here](https://stackoverflow.com/questions/26255/reserved-keywords-in-javascript). – RBT Jun 15 '17 at 08:08
  • 1
    @RBT Typescript – Aris Jun 15 '17 at 08:09

1 Answers1

1

First of all define you abstract class Y before extending it. An then you can use super keyword to access base class members. See the code below.

abstract class Y {
  public saving() {
    console.log("Y Class Saving")
  }
}
class X extends Y {
  public save() {
    super.saving();
    console.log("X Class Save")
  }
}
const x = new X();
x.save();

Can test the above code here on Playground

Hope it helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
  • What I want is a way to hook classes during runtime and giving them ability to call methods without defining them explicitly. We can do that in PHP by relying on __call, for example. So, I'm not going to do this.saving() in the save method, but rather teach my class to call saving whenever I call save. This is a good answer but I already know about it. – Aris Jun 15 '17 at 08:13
  • in PHP `If a class implements __call(), then if an object of that class is called with a method that doesn't exist __call() is called instead`. Is that what you want if the `Save()` method is not defined it should call `Saving()` method of base class?? – Manish Jun 15 '17 at 08:20
  • We use magic methods such as call in PHP to call more methods. Laravel framework for example, calls `saving` method when you call `save`. What I want is something similar. For example, if I can listen for calling methods in JS, I can simply do something like `this.saving.apply(...args)` or something like this. – Aris Jun 15 '17 at 08:33