Bar*_*ney 4 javascript methods jquery prototype object
我写了以下内容:
Object.prototype.length = function(){
var count = -1;
for(var i in this) count++;
return count;
}
Run Code Online (Sandbox Code Playgroud)
有用.但是当我执行我的页面时,即使不使用这个函数,Firebug告诉我jQuery .appendTo()不再是一个函数.为什么会这样?
该原型扩展正在破坏该$.each方法,因为此方法使用该length属性检测数组和对象(在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);
//...
Run Code Online (Sandbox Code Playgroud)
如您所见,isObj只有当变量不包含length属性(或属性值为undefined)时,该变量才为真.
如果isObj为false,jQuery将尝试使用普通for循环进行迭代:
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
Run Code Online (Sandbox Code Playgroud)
然后,appendTo使用创建方法$.each,这就是为什么没有定义:
//...
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
},
//...
Run Code Online (Sandbox Code Playgroud)
我将始终建议远离扩展Object.prototype,当您扩展此原型时,所有对象都会接收这些附加属性.
这尤其成问题,因为当您迭代对象的属性时,会出现这些新属性,从而导致各种意外行为.