我正在閱讀關於iframe resizer的源代碼here。並得到了極其混亂的這個片段在factory()
功能:在javascript中使用綁定undefined的目的是什麼?
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;
};
}
似乎element
在init()
功能iframe元素。爲什麼init.bind(undefined, options)
得到了element
參數傳遞給init()函數?這個元素來自哪裏?
但''''''init()'函數來自哪裏?它如何傳遞給該函數? – Blake
綁定的'init'用作'forEach'的回調函數;所以'forEach'遍歷'document.querySelectorAll(target ||'iframe')'並且將每個'element'依次傳遞給綁定的'init'。 – deceze
它基本上等同於'document.querySelectorAll(target ||'iframe').forEach(element => init(options,element))';然而,'querySelectorAll'不返回一個'Array',因此沒有'forEach',因此使用這個解決方法。 – deceze