My intend:
- With an object
o
with a methodwork
- Print "Hello" before
o.work()
- Print "Bye" after
o.work()
o.work()
will be called by a 3rd party
My attempt:
// sample library object
var o = {
score: 5,
work: function() {
console.log(this.score);
}
};
// my code
var cons = function () {
this.score = 10;
this.work = function () {
console. log("Hello");
// how to call parent's work() ?
// if I do this.prototype.work() -> prints 5
// But parent's work should be called when this.score is 10
console. log("Bye");
};
};
cons.prototype = o;
my_o = new cons();
// my_o will be passed to 3rd party instead of o
In short:
- I am attempting to decorate inherited method.
- Its easy with super but JavaScript doesn't have super.
They say prototypal inheritance is supirior.
Update:
work()
uses this.score, which is overridden after inheritance.
Update 2:
- Expectation is
o.work()
should print5
- Expectation is
my_o.work()
should print10