什么是appendTo中的[original]

时间:2015-08-10 21:17:48

标签: javascript jquery

我需要在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]是什么?

1 个答案:

答案 0 :(得分:1)

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 );
    };
});