编写此代码的程序员知道程序的其他部分正在此数组上调用splice,他想将一个事件附加到该数组上,以更新用户界面(因此调用了 jQuery) .
这通常称为“猴子修补”。你可以在https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/阅读它
这不是一个好的做法,因为它混淆了正在发生的事情:没有程序员会期望调用数据操作函数会在其他地方产生副作用。
您可以运行此示例以了解其工作原理:
const myArray = [];
// Patch push method only for this instance of array.
myArray.push = function() {
// log event
console.log('myArray.push was called with the following arguments', arguments);
// Call the original push function with the provided arguments.
return Array.prototype.push.apply(this, arguments);
}
myArray.push(1);
您还可以为给定类的所有实例修补方法:
// Patch push method on all arrays
const originalPush = Array.prototype.push;
Array.prototype.push = function() {
// log event
console.log('.push was called with the following arguments', arguments);
// Call the original push function with the provided arguments.
return originalPush.apply(this, arguments);
}
const myArray = [];
myArray.push(1);
关于arguments 的问题,在javascript 中,所有函数都可以访问arguments 类数组对象,该对象包含调用函数时使用的参数,这与原始声明中指定的参数无关.
function doSomething(arg1) {
console.log(arguments[2]);
}
doSomething(1, 2, 3); // outputs "3"
这里是关于它的 MDN 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments