javascript - array.splice = what does it means?
问题描述
I would like to understand the meaning of that code fragment. "saveTo" is a array, the programmer assigned a function() to the splice method. I don't understand what does it mean. Is that a override? What is the meaning of the return argument?, and why the function takes no argument while splice requires 2 or more arguments?
saveTo.splice = function() {
if (saveTo.length == 1) {
$("#send").prop("disabled", true);
}
return Array.prototype.splice.apply(this, arguments);
};
解决方案
Javascript lets you re-assign methods at runtime. In this case, what the programmer was doing is reassigning splice
on this specific instance of an array in order to call a jQuery method. Beyond that, it works in exactly the same way as the existing splice as they are calling return Array.prototype.splice.apply(this, arguments);
- meaning that this method just passes on whatever arguments
are passed to it.
Here's a demo:
var myArray = [1,2,3,4];
console.log("Splice before re-assing: ", myArray.splice(1,1));
// reset it.
myArray = [1,2,3,4];
myArray.splice = function(){
console.log("From inside new splice function");
return Array.prototype.splice.apply(this, arguments);
}
console.log("Splice after re-assiging: ", myArray.splice(1,1));
Whether this is a good thing to do is debatable. It breaks a few principles of programming.
推荐阅读
- scala - Scala 类型类模式与模式匹配或重载
- sql - 使用默认约束值更新字段
- apache-spark-sql - Spark SQL from_json 文档
- c# - 如何在 XtraInputBox 中仅接受数值以及如何检查单击了哪个按钮?
- webusb - Google Chrome WebUSB API requestDevices() 看不到条形码扫描仪 Voyager 1450g
- c++ - 结构异常的 C++ 清除向量
- swift - 如何在swift中逐步更改UILabel文本
- python - 提取 2 个字符串之间的字符串,如果未找到第 2 个字符串,则提取到末尾
- byobu - 保存 byobu-ctrl -a 状态
- r - Stan多项式回归参数估计模型回顾