向对象原型添加可枚举函数时未捕获类型错误

Uncaught TypeError when adding enumerable function to Object prototype

每当我向 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 文件中重现错误。

I get a few type errors whenever I add an enumerable function to the prototype of 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,请使用 non-enumerable 属性。 (不过请注意,即使使用 non-enumerable Object.prototype 属性也很容易引入不兼容性。)如果您需要支持不支持它的过时浏览器,则需要单独保留 Object.prototype .