37

.js在我的页面中添加了一个简单的文件,其中添加了一些非常普通的常见任务类型的函数到ObjectArray原型中。

通过反复试验,我发现在 jQuery 中添加任何函数Object.prototype,无论其名称或功能如何都会导致 jQuery 中的 Javascript 错误:

罪魁祸首?

Object.prototype.foo = function() {
    /*do nothing and break jQuery*/
};

jquery-1.3.2.js在 attr:function { } 声明中得到第 1056 行的错误:

/*Object doesn't support this property or method*/
name = name.replace(/-([a-z])/ig, function(all, letter) {
            return letter.toUpperCase();
        });

显然 G.replace 是未定义的。

虽然很明显有些东西我只是没有用原型设计来解决我的问题,但我很难弄清楚它是什么。

需要明确的是,我不是在寻找解决方法,我已经处理了......我正在寻找的是为什么?. 为什么要添加一个函数来Object.prototype破坏这段代码?

4

5 回答 5

47

如果这只是弄乱 for...in 循环的情况,您不能使用 Object.defineProperty 添加您的 fn 而不使其可枚举吗?

所以:

Object.defineProperty(Object.prototype, "foo", { 
    value: function() {
        // do stuff
    },
    enumerable : false
});

似乎对我有用。这还会被认为是不好的形式吗?

于 2011-05-04T23:20:35.623 回答
21

你永远不应该扩展Object.prototype. 它所做的不仅仅是破坏 jQuery;它完全打破了 Javascript 的“object-as-hashtables”特性。不要这样做。

你可以问 John Resig,他也会告诉你同样的事情

于 2009-12-01T17:14:04.813 回答
5

我同意,添加一些东西Object.prototype需要谨慎,应该避免。寻找其他解决方案,例如:

将其添加到 Object ,然后根据需要使用callor访问它apply。例如:

Object.foo = function () { return this.whatever()}

然后通过以下方式在对象上调用它:

Object.foo.call(Objname);  // this invokes the function as though it were a
                           // method of Objname.  That is, its like Objname.foo()

为了好玩,您可以添加以下内容(是的,我知道这有点危险......):

Function.using = Function.call; // syntactic sugar

现在你可以写Object.foo.using(Objname)了,它读起来就像一句句子。

但作为一项规则,请远离更改任何大型原型。

于 2010-03-13T07:44:43.603 回答
2

我想在我的所有对象中实现“真正的”面向对象,就像这样:

interface Object
{
    GetType: () => string;
    ToString: () => string;
    GetHashcode: () => number;
    Equals: (obj: any) => boolean;
}

由于 Object.prototype 破坏了 JQuery,我默认使用上述解决方案来使用 defineProperty 但这不接受任何参数。

好消息是您可以破解 defineProperty 并实际接受参数。这是我的实现:

Object.defineProperty(Object.prototype, "Equals",
    {
        value: function (obj: any)
        {
            return obj == null && this == null
                    ? true
                    : obj != null && this == null
                        ? false
                        : obj == null && this != null
                            ? false
                            : this.GetHashcode() == obj.GetHashcode();
        },
        enumerable: false
    });

这有效,不会与 JQuery 冲突。

于 2016-02-24T12:43:54.077 回答
-1

我怀疑向 Object.prototype 添加函数会直接破坏 jQuery。只需确保整个站点中的每个 for..in 循环都包含在 hasOwnProperty 检查中,因为您已全局添加该函数,并且迭代它的结果可能是不可预测的:

Object.prototype.foo = function() {};    
var myObject = {m1: "one", m2: "two" };

for(var i in myObject) { if(myObject.hasOwnProperty(i)) {
   // Do stuff... but not to Object.prototype.foo
}}
于 2009-12-01T17:01:32.797 回答