繁体   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