// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[ i] ) {}
}
}
return object;
},
分析:jquery文档说 each(callback)作用是以每一个匹配的元素作为上下文来执行一个函数。就是用each来遍历数组,来执行同一个方法
这个方法的实现最关键的是:call与apply的用法:call(apply)就是将函数的对象的从初始的上下文改为thisObj指向的对象,
就是说用thisObj来代替原来的对象来执行方法:call与apply的第一个参数为this指向的对象,而后面的参数都下传给函数的,
call传给函数的参数用逗号分隔而apply则为一个数组。
//1.callback.apply( object[ name ], args )
//2.callback.call( object[ name ], name, object[ name ] )
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn