为什么数组上的自定义方法无效:
function runTestMethod() {
alert("method running");
}
String.prototype.testMethod = runTestMethod;
var A = "A";
A = A.testMethod(); // WORKS
var B = new Array();
B[0] = "food";
B[1] = "bar";
B = B.testMethod(); // ERROR 'undefined' IS NOT A FUNCTION
B[0] = B[0].testMethod(); // ERROR 'undefined' IS NOT A FUNCTION
B[0] = B[0].slice(0,-1); // WORKS
更新:答案是我正在尝试在数组上使用 String.prototype 。我的方法需要是 Array.prototype 。尽管数组“B”包含字符串成员,但它们仍被视为数组对象属性而非实际字符串。 slice()的工厂方法设计混乱,无法处理字符串和数组。感谢T.J.克劳德的解释。
答案 0 :(得分:2)
因为您已将其放在String.prototype
上,而不是Array.prototype
。
这一行:
String.prototype.testMethod = runTestMethod;
添加到String.prototype
,因此字符串上提供了属性(及其引用的函数)。您想要添加到Array.prototype
,以便数组上可以使用属性(及其引用的函数)。
完整示例:
// v--- Notice this is `Array.prototype`!
Array.prototype.oddsOnly = function() {
var rv = [], index;
for (index = 1; index < this.length; index += 2) {
rv.push(this[index]);
}
return rv;
};
// These are arrays
var a = ["zero", "one", "two", "three", "four", "five", "six"];
var b = a.oddsOnly();
// ^------------- function is available on arrays
console.log("a: " + a.join(", "));
console.log("b: " + b.join(", "));
输出:
a: zero, one, two, three, four, five, six b: one, three, five