0
var object = {}; //lots of stuff in here

var func = object.dosome;

object.dosome = function(a,b) {
    func(a,b);
    //someth else here i need to add 
}

This works but ugly.
So is there a way to supplement object.dosome method, without creating a new variable containing it's function?
Some sort of parent.dosome?

1
  • are you trying to simulate polymorphism?
    – user2844991
    Oct 8, 2015 at 14:06

2 Answers 2

0

maybe create a class Object and define in its protoype the dosome() method.

var Object =  new function() {}; //lots of stuff in here

Object.prototype.dosome = function(a,b) {
    func(a,b);
}
//and then
var myObject = new Object();
0

I think you should read a little about JS OOP. ES6 adds some nice syntactic sugar that can help you achieve what you want in fewer lines of code. Read more here.

However, if you don't want to have problems with the prototype chains, here's a simpler way of achieving what you want:

function chain (baseFunc, func) {
  return function () {
     var args = [].slice.call(arguments, 0);
     args.unshift(baseFunc);
     return func.apply(this, args);
  };
}

Usage:

var obj = { 
  doSome: function (a, b) { return a + b; } 
};

obj.doSome(4, 5); // 9

obj.doSome = chain(obj.doSome, function (baseFunc, a, b) {
   var result = baseFunc(a, b);   
   return result + 10;
});

obj.doSome(4, 5); // 19

You can go one step further and get rid of the assignment:

function extend (instance, method, func) {
    instance[method] = chain(instance[method], func);
}

extend(obj, "doSome", function (baseFunc, a, b) {
    var result = baseFunc(a, b);   
    return result + 2;
});

obj.doSome(4, 5); // 21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.