Javascript 中的自定义方法实现模式



我在Javascript中找到了这种语法:

myVariable = myClass.prototype.simpleMethod;
myClass.prototype.simpleMethod = function(params)
{
myVariable.apply(this, arguments);
....
};

这种模式的目的是什么? 新功能是否结合了新旧实现?还是将其替换为"...."? 你能提供详细的解释吗?

编辑:问题解决了。我将 Nas 答案标记为已接受,但花费者的答案也可能是相关的。

它相当于调用原始基本实现的重写。原始实现存储在变量中。现在,原始实现被新函数覆盖。新函数做的第一件事(调用myVariable.apply(this, arguments))是使用相同的参数调用原始实现,确保保留this。有关更多详细信息,请参阅Function.prototype.apply

arguments是 JavaScript 运行时在任何被调用函数的上下文中提供的变量。它是一个数组,其中包含传递给当前执行的函数(即调用堆栈中最直接的函数)的参数。详情请看这里。

这是一种包装和"扩展"simpleMethod的方法。

如果要在运行方法之前和/或之后定义行为,则此功能可能很有用。

以下是对示例中每个语句的作用的逐行说明。

// We save a reference to the current implementation of the "simpleMethod"
myVariable = myClass.prototype.simpleMethod;
// We change the "simpleMethod" implementation to have a "new implementation"
myClass.prototype.simpleMethod = function(params)
{
// as myVariable store "the old" implementation we call the old impl. 
// having the same this as the wrapping function.
// passing the same args, passed to the "wrapper function"
myVariable.apply(this, arguments);
....
};

参数对象是所有非箭头函数中可用的局部变量。您可以使用函数的参数对象在该函数中引用函数的参数。它包含调用函数的每个参数的条目,第一个条目的索引为 0。 (来自MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)

最新更新