簡體   English   中英

在JavaScript中使用未定義綁定的目的?

[英]The purpose of using bind undefined in javascript?

我在這里閱讀有關iframe調整程序的源代碼。 並在factory()函數中對該代碼段感到非常困惑:

Array.prototype.forEach.call(
                    document.querySelectorAll( target || 'iframe' ),
                    init.bind(undefined, options)
                );

factory()函數:

function factory(){
    function init(options,element){
        function chkType(){
            if(!element.tagName) {
                throw new TypeError('Object is not a valid DOM element');
            } else if ('IFRAME' !== element.tagName.toUpperCase()) {
                throw new TypeError('Expected <IFRAME> tag, found <'+element.tagName+'>');
            }
        }

        if(element) {
            debugger
            chkType();
            setupIFrame(element, options);
            iFrames.push(element);
        }
    }

    var iFrames;

    setupRequestAnimationFrame();
    setupEventListeners();

    return function iFrameResizeF(options,target){
        iFrames = []; //Only return iFrames past in on this call

        switch (typeof(target)){
        case 'undefined':
        case 'string':
            Array.prototype.forEach.call(
                document.querySelectorAll( target || 'iframe' ),
                init.bind(undefined, options)
            );
            break;
        case 'object':
            init(options,target);
            break;
        default:
            throw new TypeError('Unexpected data type ('+typeof(target)+')');
        }

        return iFrames;
    };
}

似乎該elementinit()函數中的iframe元素。 為什么init.bind(undefined, options)element參數傳遞給init()函數? 這個元素從哪里來?

.bind()創建一個新函數, this函數的上下文將設置為第一個參數,其他參數將設置為以下參數。 為了說明這意味着什么:

function foo(bar, baz) {}

var f = foo.bind({});
f(1, 2);

調用f這里, this將被設置為{} bar1baz2

var f = foo.bind({}, 1);
f(2);

這實際上具有相同的結果, bar1baz2

var f = foo.bind({}, 1, 2);
f();

同樣,同樣的結果。

您不僅可以bind this的值,還可以綁定參數。

所以:

init.bind(undefined, options)

init顯然不需要this ,因此使用undefined可以跳過該參數,並且init的第一個參數必定是options 以后要調用此綁定函數的任何人都可以傳遞其他參數。 這里的bind用於綁定第一個參數; 您只需要首先為this參數傳遞任何內容即可

看一下如何使用該工廠的API,因為它將闡明元素的來源。 基本上,調用工廠函數factory()會返回函數iFrameResizeF()。 然后,您可以使用一個或兩個參數調用該函數。

使用一個參數,您可以向其發送選項,也可以向其發送作為CSS選擇器的字符串。 如果您將選項發送給它,它將使用這些選項在DOM中的所有iframe上綁定init()。 如果發送一個字符串,它將在選擇器獲得的所有元素上綁定init(),而沒有任何選項。

使用兩個參數,它將使用所有這些選項將init()綁定到所有這些元素上。

一旦您運行了該元素的初始化,就將選擇正確的選項。

所以在代碼中就像:

var useFactory = factory();
// Two parameters
useFactory( {"option1" : "value1", "option2" : "value2"}, "selectorString" );
// Or only parameters so all iframes are affected
useFactory( {"option1" : "value1", "option2" : "value2"} );
// Or only a selector so the options will be set to undefined for all elements matching the selector
useFactory( "selectorString" );

然后在代碼中的其他地方,可能會調用這些元素上的那些初始化函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM