所以我编写了一个函数来扩展对象来计算其中有多少条目,因此可以这样使用:
test = {"foo": "bar", "baz": 7, "darth": "maul"}
test.count()
=> 3
我这样写代码:
Object.prototype.count = function() {
var count = 0, key;
for (key in this) {
if (this.hasOwnProperty(key)) {
count++;
}
}
return count;
}
这是我第一次尝试使用原型(prototype)进行扩展,我从 jQuery.js 中收到此错误:
Uncaught TypeError: Object function () {
var count = 0, key;
for (key in this) {
if (this.hasOwnProperty(key)) {
count++;
}
}
return count;
} has no method 'replace'
堆栈跟踪指向我在 jQuery 对象 onLoad 上调用 css
的位置:
$img.css({left: 20, top: 50});
并不是说我认为该行有任何具体内容,但我认为提供它可能会很好。
我在这里做错了什么吗?
最佳答案
一个教训,说明为什么扩展 native 类型的原型(prototype)可能是一个坏主意。 :)
在 jQuery
中的某个位置,它正在测试一个通用对象是否存在名为 count
的属性,然后将其视为字符串。由于您现在已经使该属性始终存在,因此它找到了它,但它不是一个字符串(如预期的那样)并破坏了代码。
关于javascript - 扩展对象导致 jQuery 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11655907/