我需要在jQuery中编写自己的appendTo,因此必须引用jQuery源,我在jQuery源中看到以下代码:
function (selector) {
var elems, i = 0,
ret = [],
insert = jQuery(selector),
last = insert.length - 1;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply(ret, elems.get());
}
return this.pushStack(ret);
}
现在我在appendTo的jQuery代码中看到以下行:
jQuery(insert[i])[original](elems);
这里的
[original]
是什么? 最佳答案
site you linked仅显示函数的来源,没有显示其周围范围(通过Function.prototype.toString
)。与actual source进行比较时,可以看到original
变量来自外部作用域:
jQuery.each({
appendTo: "append", // <<< This key-value pair...
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) { // <<< ...is bound to these arguments
jQuery.fn[ name ] = function( selector ) { // <<< The function from the OP
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android<4.1, PhantomJS<2
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
关于javascript - 什么是appendTo中的[原始],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31929362/