我试图为Object创建一个length()方法的原型,并破坏了jQuery –怎么做? [英] I tried to prototype a length() method to Object and broke jQuery – how?

查看:116
本文介绍了我试图为Object创建一个length()方法的原型,并破坏了jQuery –怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下内容:

Object.prototype.length = function(){
    var count = -1;
    for(var i in this) count++;
    return count;
}

有效.但是当我执行页面时,即使不使用此函数,Firebug也会告诉我jQuery的.appendTo()不再是一个函数.为什么会这样?

It works. But when I execute my page, even without using this function, Firebug tells me that jQuery's .appendTo() is no longer a function. Why would this be?

推荐答案

该原型扩展正在破坏

That prototype extension is breaking the $.each method, because this method detects between arrays and objects using the length property (in jQuery 1.4.2):

// core.js Line 533
each: function( object, callback, args ) {
    var name, i = 0,
        length = object.length, // <--- your function from Object.prototype
        isObj = length === undefined || jQuery.isFunction(object);
//...

如您所见,isObj变量只有在不包含length属性(或属性值为undefined)时才为true.

As you can see, the isObj variable will be true only if it doesn't contains a length property (or the property value is undefined).

如果isObj为false,则jQuery将尝试使用普通的for循环进行迭代:

If isObj is false, jQuery will try to iterate using a normal for loop:

for ( var value = object[0];
    i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}

然后,使用$.each创建appendTo方法,这就是为什么未定义的原因:

Then, the appendTo method is created using $.each, that's why is not defined:

//...
jQuery.each({
    appendTo: "append",
    prependTo: "prepend",
    insertBefore: "before",
    insertAfter: "after",
    replaceAll: "replaceWith"
},
//...

我将始终建议,以免扩展Object.prototype,当您扩展此原型时, ALL 对象将获得这些附加属性.

I will always recommend to stay away from extending Object.prototype, when you extend this prototype ALL objects receive those additional properties.

这特别有问题,因为当您遍历对象的属性时 这些新属性出现,导致各种意外行为.

This is especially problematic since when you iterate over the properties of the object these new properties appear, causing all sorts of unexpected behavior.

这篇关于我试图为Object创建一个length()方法的原型,并破坏了jQuery –怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆