0

I have an object called a that I use nearly all the time.

Then 'b' comes along being awkward and I need to do some other things before calling notify.

What is the best functional/prototypical approach to take get the same thing has called the parent in object-oriented (Which I understand to not be possible without using Javascript classes - correct me if I'm wrong)

let a = {};

a.notify = () => {
    doSomethingCool();
}

var b = Object.create(a);

b.notify = () => {
    doCoolStuffFirst();
    doSomethingCool();
}
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
Positonic
  • 9,151
  • 14
  • 57
  • 84

3 Answers3

0

It's not quite clear what you're asking. Are you simply looking for

const notify_orig = b.notify;
b.notify = () => {
    doCoolStuffFirst();
    notify_orig.call(b);
}

?

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

As you say, it is easy with classes:

class A {
  notify() {
    doSomethingCool();
  }
}

class B {
  notify() {
    doCoolStuffFirst();
    super.notify();
  }
}

Without ES6 classes, you're in for a rough ride. ES6 compiler translates super.notify() into something like

_get(
   B.prototype.__proto__ ||
   Object.getPrototypeOf(B.prototype),
   "notify", this
).call(this);

(with _get being a kind-of-huge utility method to smooth the rough edges about different kinds of values and inheritance and stuff). It's not impossible, it's just complicated enough that you probably don't want to do it by yourself.

Amadan
  • 191,408
  • 23
  • 240
  • 301
0

Without using __proto__ or class (which is syntactic sugar in ES6).

function doSomethingCool() {
    console.log("something cool");
}

function doCoolStuffFirst() {
    console.log("cool stuff first");
}

let a = {};
a.notify = () => {
    doSomethingCool();
}
a.notify();

let b = Object.create(a)
b.notify = (() => {
    let notifySuper = b.notify; // reference to the 'super' method
    return () => {
        doCoolStuffFirst();
        notifySuper();
    }
})();
b.notify();
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33