简体   繁体   English

如何使用普通 JS 将 IIFE 中的变量重新使用到另一个变量?

[英]How to re use a variable from an IIFE to another using plain JS?

I wrote a function, initialize that immediately invokes two other functions within an object.我写了一个 function, initialize它立即调用 object 中的其他两个函数。 I want to reuse the boardXs variable on toggleSymbol .我想在toggleSymbol上重用boardXs变量。 Therefore, I thought of returning it to initialize 's scope hoping it would work.因此,我想把它退回来initialize scope 希望它能起作用。

const game = {
    initialize: (function() {
        (function hideX() {
            let boardXs = document.querySelectorAll('#ghost > div');
            for (let i = 0; i < boardXs.length; i++) {
                boardXs[i].innerHTML = " ";
            };
            return {boardXs};
        })(),

        (function toggleSymbol() {
            console.log(boardXs)
        })();
    });
}

As I run game.initialize() in the console, hideX works but an error is thrown in the console: "boardXs is not defined".当我在控制台中运行game.initialize()时, hideX工作但在控制台中抛出错误:“boardXs 未定义”。

What is going on?到底是怎么回事? How can I use variables amongst IIFEs?如何在 IIFE 中使用变量? For the sake of learning, I'd like to continue using this IIFE setup, if possible.为了学习,如果可能的话,我想继续使用这个 IIFE 设置。

You can do this if you are returning the object from hideX and use it in toggleSymbol .如果您从hideX返回 object 并在toggleSymbol中使用,您可以执行此操作。

If you are returning the object from the hideX , then you need to store the returned value in a variable and use that variable in scope or its nested scope.如果要从 hideX 返回hideX ,则需要将返回值存储在变量中,并在 scope 或其嵌套的 scope 中使用该变量。

 const game = { initialize: (function() { // Grab object in result const result = (function hideX() { let boardXs = document.querySelectorAll('#ghost > div'); for (let i = 0; i < boardXs.length; i++) { boardXs[i].innerHTML = " "; }; return { boardXs }; })(); // use here (function toggleSymbol() { console.log(result) })(); }) } game.initialize();
 <div id="ghost"> <div> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM