Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 extends a class, I want them to effectively be extending this function. This is the user's code for instance:

// In the child instance
function xyz()
{
    var y = 2;
}

Merging should result in:

// In the merged instance
function xyz()
{
    var x = 1;
    var y = 2;
}
like image 353
Antony Carthy Avatar asked Sep 02 '11 17:09

Antony Carthy


3 Answers

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.

like image 109
Matt Avatar answered Oct 15 '22 20:10

Matt


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

var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

/* merge object2 into object1 */
$.extend(object1, object2);

or use prototype chain to implement inheritance. for example:

function a() {
    this.t1 = 1;
    this.sayMyName = function() {
        alert('a');
    }
}
b.prototype = new a;
b.prototype.constructor = b;
function b() {
    this.t2 = 2;
    this.sayMyName = function() {
        alert('b');
    }
}
var obj = new b();
alert(obj.t1); // this would say 1
obj.sayMyName(); // this would say b
like image 29
ntangjee Avatar answered Oct 15 '22 21:10

ntangjee


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

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

let y = function () {
  console.log("world")
}
mergeFunctions(x, y)()
/////////////////////
hello
world
like image 32
Jackstine Avatar answered Oct 15 '22 20:10

Jackstine