扩展一个函数——合并两个函数

Extend a function - merge two functions?

本文关键字:函数 两个 合并 一个 扩展      更新时间:2023-09-26

创建Javascript '类'的最佳方式是什么?例如

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

我想在类中设置这个,当用户扩展一个类时,我想让他们有效地扩展这个函数。以下是用户代码,例如:

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

合并应该导致:

// In the merged instance
function xyz()
{
    var x = 1;
    var y = 2;
}

你不能像你描述的那样'合并'函数,但你可以做的是让一个函数被重新定义为调用自己和一个新函数(在原始函数之前或之后)。

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);
};

如果您不关心执行上下文或被调用的函数是无参数的,则不需要包含(this, arguments)。但是,如果您想要一个参数化的方法,我将其包含在内是为了清楚地说明您可能会做什么。

您用jquery标记问题,所以我假设您使用jquery。使用jquery,您可以使用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);

或使用原型链实现继承。例如:

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

如果我理解正确,您可以尝试重命名原始函数并在新函数中调用它:

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

也适用于类/方法继承:

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