Skip to content Skip to sidebar Skip to footer

Extend A Function - Merge Two Functions?

What is the best way to have a Javascript 'class', for instance // In the parent instance function xyz() { var x = 1; } I want to set this in the class, and when a user extend

Solution 1:

You can't 'merge' functions as you describe them there, but what you can do is have one function be redefined to call both itself and a new function (before or after the original).

var xyz = function(){
   console.log('xyz');
};

var abc = function(){
   console.log('abc');
};

// and, elsewhere, if you want to merge:var orig = abc;
abc = function(){
    orig.call(this, arguments);
    xyz.call(this, arguments);
};

The inclusion of (this, arguments) is not needed if you don't care about execution context or if the called function is parameterless. But I included for clarity of what one might do if you wanted a parameterized method.

Solution 2:

You tag the question with jquery, so I assume you use jquery. with jquery, you could merge objects with jQuery.extend().

varobject1= {
  apple:0,
  banana: {weight:52, price:100},
  cherry:97
};varobject2= {
  banana: {price:200},
  durian:100
};/*mergeobject2intoobject1*/$.extend(object1,object2);

or use prototype chain to implement inheritance. for example:

functiona() {
    this.t1 = 1;
    this.sayMyName = function() {
        alert('a');
    }
}
b.prototype = new a;
b.prototype.constructor = b;
functionb() {
    this.t2 = 2;
    this.sayMyName = function() {
        alert('b');
    }
}
var obj = newb();
alert(obj.t1); // this would say 1
obj.sayMyName(); // this would say b

Solution 3:

const mergeFunctions = function () {
  let listOfFuncs = []
  for (let func ofarguments) {
      listOfFuncs.push(func)
  }
  returnfunction () {
    for (let func of listOfFuncs) {
        func(arguments)
    }
  }
}

let x = function () {
  console.log("hello");
}

let y = function () {
  console.log("world")
}
mergeFunctions(x, y)()
/////////////////////
hello
world

Solution 4:

If I understand you correctly, you can try renaming the original function and calling it within the new function:

// In the parent instancefunctionxyz()
{
    var x = 1;
}

// In the child instancevar old_xyz = xyz;
functionxyz()
{
    var y = 2;
    old_xyz();
}

Also works with class/method inheritance:

MyClass.prototype.old_xyz = MyClass.prototype.xyz;
MyClass.prototype.xyz = function () {
    this.old_xyz();
}

Post a Comment for "Extend A Function - Merge Two Functions?"