簡體   English   中英

了解ready中的匿名函數如何被調用

[英]Understand how the anonymous function in ready gets called

我在這里只是通過這段代碼,它描述了如何在純js中創建自己的自定義ready函數。 答案被詳細解釋,我已經在js中編程了一段時間了,但是在理解代碼的初始部分時仍然有一個問題,請再次看下面的代碼:

(function(funcName, baseObj) {
    // The public function name defaults to window.docReady
    // but you can pass in your own object and own function name and those will be used
    // if you want to put them in a different namespace
    funcName = funcName || "docReady";
    baseObj = baseObj || window;
    var readyList = [];
    var readyFired = false;
    var readyEventHandlersInstalled = false;

    // call this when the document is ready
    // this function protects itself against being called more than once
    function ready() {
        if (!readyFired) {
            // this must be set to true before we start calling callbacks
            readyFired = true;
            for (var i = 0; i < readyList.length; i++) {
                // if a callback here happens to add new ready handlers,
                // the docReady() function will see that it already fired
                // and will schedule the callback to run right after
                // this event loop finishes so all handlers will still execute
                // in order and no new ones will be added to the readyList
                // while we are processing the list
                readyList[i].fn.call(window, readyList[i].ctx);
            }
            // allow any closures held by these functions to free
            readyList = [];
        }
    }

    function readyStateChange() {
        if ( document.readyState === "complete" ) {
            ready();
        }
    }

    // This is the one public interface
    // docReady(fn, context);
    // the context argument is optional - if present, it will be passed
    // as an argument to the callback
    baseObj[funcName] = function(callback, context) {
        // if ready has already fired, then just schedule the callback
        // to fire asynchronously, but right away
        if (readyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        } else {
            // add the function and context to the list
            readyList.push({fn: callback, ctx: context});
        }
        // if document already ready to go, schedule the ready function to run
        if (document.readyState === "complete") {
            setTimeout(ready, 1);
        } else if (!readyEventHandlersInstalled) {
            // otherwise if we don't have event handlers installed, install them
            if (document.addEventListener) {
                // first choice is DOMContentLoaded event
                document.addEventListener("DOMContentLoaded", ready, false);
                // backup is window load event
                window.addEventListener("load", ready, false);
            } else {
                // must be IE
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            readyEventHandlersInstalled = true;
        }
    };
})("docReady", window);

我這樣調用代碼:

docReady(function() {
        alert('hello');
  }, window); 

我的問題是,如何像這樣調用匿名函數? ..我完全困惑:(

甚至下面的代碼如何工作?

docReady(function() {
        alert('hello');
  }, window);

我的意思是沒有定義明確的docReady函數,如下所示:

  docReady function (param1, param2);

我所看到的只是docReady作為參數傳遞給匿名函數嗎?

baseObj[funcName] = function(callback, context) {

相當於

window["docReady"] = function(callback, context) {

它將函數聲明為window的屬性(全局對象),這意味着您可以使用

window["docReady"](function() {
    alert('hello');
}, window);

或搭配

window.docReady(function() {
    alert('hello');
}, window);

甚至

docReady(function() {
        alert('hello');
}, window);

因為全局對象的屬性也是全局作用域(以及陰影之前的任何內部作用域)的變量。

關鍵位是baseObj[funcName] = function

此時, baseObj是(或至少可以是) windowfuncName是(或可以是) docReady

因此,此時它向window (全局)添加了一個名為“ docReady”的函數

window和“ docReady”作為默認參數傳遞到最后一行

})("docReady", window);

其中在頂部將函數作為參數輸入(function(funcName, baseObj) {

NB當我說baseObj是(或至少可以) window ,那是因為你可以重寫此值,則該行:

funcName = funcName || "docReady";
baseObj = baseObj || window;

如果未提供替代方法, baseObj funcName設置為“ docReady”和baseObj ,這意味着您可以根據需要更改它們,因此如果最后一行更改為})("getReady", myObject); 該函數將稱為getReady並將其添加到myObject而不是全局window

您正在閱讀錯誤的代碼。

檢查以下行:

(function(funcName, baseObj) {
    ...
    baseObj[funcName] = function(callback, context) {
        ...
    };
    ...
})("docReady", window);

它將為baseObj添加一個新屬性,在本例中為window 該屬性是您調用的函數。 docReady 全局的所有東西都不需要像window.something這樣的名字。 這就是為什么您使用docReady的原因。

暫無
暫無

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

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