每当我向 Object 的原型添加可枚举函数时,我都会收到一些类型错误。
jquery-1.10.2.js:2451 Uncaught TypeError: matchExpr[type].exec is not a function
at tokenize (jquery-1.10.2.js:2451)
at Function.Sizzle [as find] (jquery-1.10.2.js:1269)
at init.find (jquery-1.10.2.js:5744)
at change-project-controller.js:4
at change-project-controller.js:255
tokenize @ jquery-1.10.2.js:2451
Sizzle @ jquery-1.10.2.js:1269
find @ jquery-1.10.2.js:5744
(anonymous) @ change-project-controller.js:4
(anonymous) @ change-project-controller.js:255
jquery-1.10.2.js:2451 Uncaught TypeError: matchExpr[type].exec is not a function
at tokenize (jquery-1.10.2.js:2451)
at Function.Sizzle [as find] (jquery-1.10.2.js:1269)
at init.find (jquery-1.10.2.js:5744)
at filter-by-registrant-controller.js:10
at filter-by-registrant-controller.js:179
tokenize @ jquery-1.10.2.js:2451
Sizzle @ jquery-1.10.2.js:1269
find @ jquery-1.10.2.js:5744
(anonymous) @ filter-by-registrant-controller.js:10
(anonymous) @ filter-by-registrant-controller.js:179
jquery-1.10.2.js:2451 Uncaught TypeError: matchExpr[type].exec is not a function
at tokenize (jquery-1.10.2.js:2451)
at Function.Sizzle [as find] (jquery-1.10.2.js:1269)
at init.find (jquery-1.10.2.js:5744)
at registrations-controller.js:6
at registrations-controller.js:412
tokenize @ jquery-1.10.2.js:2451
Sizzle @ jquery-1.10.2.js:1269
find @ jquery-1.10.2.js:5744
(anonymous) @ registrations-controller.js:6
(anonymous) @ registrations-controller.js:412
Index:290 Uncaught TypeError: Cannot read property 'registerFilter' of undefined
at Index:290
(anonymous) @ Index:290
请注意,四个错误中的最后一个与 jQuery 无关。
这是导致错误发生的代码:
Object.defineProperty(Object.prototype, "select", {
enumerable: true,
value: function () {
return "hello world";
}
});
如果我将函数添加为不可枚举,我不会收到错误,如下所示:
Object.defineProperty(Object.prototype, "select", {
enumerable: false,
value: function () {
return "hello world";
}
});
请注意,唯一的区别是可枚举成员设置为 false
。此外,如果我更改要添加到数组而不是对象中的可枚举函数,则代码运行良好。
我正在从事的项目不是我的,所以我无法共享它,并且我没有成功地在 jsfiddle 或简单的 HTML 文件中重现错误。
每当我向 Object 的原型添加可枚举函数时,我都会收到一些类型错误。
别这样。正如你所发现的,这样做会破坏很多毫无戒心的代码。事物的默认状态是空白对象没有可枚举的属性。例如:
var o = {};
for (var name in o) {
console.log("This line never runs in a reasonable world.");
}
console.log("End");
通过将可枚举属性添加到 Object.prototype
,可以打破它:
Object.prototype.foo = function() { };
var o = {};
for (var name in o) {
console.log("I wasn't expecting to find: " + name);
}
console.log("End");
向Object.prototype
添加内容几乎从来都不是一个好主意。向其添加可枚举的内容始终是一个坏主意™。所有现代浏览器都支持defineProperty
,所以如果你必须扩充Object.prototype
,请使用不可枚举的属性。(但请注意,即使使用不可枚举的Object.prototype
属性,也很容易引入不兼容性。如果您需要支持不支持它的过时浏览器,则需要不要管Object.prototype
。