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;
}
                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.
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
                        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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With