开发者

Extend a function - merge two functions?

开发者 https://www.devze.com 2023-04-01 21:12 出处:网络
What is the best way to have a Javascript \'class\', for instance // In the parent instance function xyz()

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
func开发者_如何学Pythontion 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 I understand you correctly, you can try renaming the original function and calling it within the new function:

// In the parent instance
function xyz()
{
    var x = 1;
}

// In the child instance
var old_xyz = xyz;
function xyz()
{
    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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消