Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorate prototype and call parent function

Tags:

javascript

I am trying to decorate some object for example:

Object.prototype.someFunc = function(x) {
  if (x == 1) {
      return x;
  } 

  return super.someFunc() // <-- ? 
}

How can I call the function that I'm overriding, on the second return statement?

like image 246
David Mana Avatar asked Aug 07 '26 01:08

David Mana


1 Answers

You could take advantage of inheritance:

function Parent() { }

Parent.prototype.someFunc = function(x) {
    var result = 0;
    if (x == 1) {
        result = 1;
    }
    return result;
}

function Child() { }

Child.prototype = Object.create(Parent.prototype); //inheritance
Child.prototype.constructor = Child; //enforce the constructor to be Child instead of Parent

Child.prototype.someFunc = function(x) {
    return Parent.prototype.someFunc.call(this, x); //call your Parent prototype someFunc passing your current instance
}

var child = new Child();
console.log(child.someFunc(1)); //1
console.log(child.someFunc(2)); //0

Avoid to extend native prototypes. See https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

like image 162
roland Avatar answered Aug 08 '26 14:08

roland