search

Home  >  Q&A  >  body text

node.js - JavaScript self-executing function problem, please give me some advice

I asked this question once before but did not get the result. Maybe my description was not clear enough. Now I have reorganized my thoughts. The details are as follows:

function demo(){
    // 各种实现
}
demo();    // 我希望它默认就执行一次,所以就这么调用了。

窗口事件:
$(window).resize(function(){
    demo();    // 这里也需要根据条件调用demo函数
});

The question is, is there a way to make the demo execute automatically for the first time? And then it can be called elsewhere? How to optimize such a code body, exclude: arguments.callee, please give me some advice... Thank you in advance.

PHP中文网PHP中文网2751 days ago465

reply all(5)I'll reply

  • 世界只因有你

    世界只因有你2017-05-16 13:44:41

    demo=(function(){
        temp()    // 默认就执行一次
        return temp
    })()
    
    function temp(){
     // 各种实现
    }
    
    窗口事件:
    $(window).resize(function(){
        demo();    // 这里也需要根据条件调用demo函数
    });

    I don’t know if this meets the requirements of the original poster

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:44:41

    There are many ways to achieve it. Both anonymous functions and self-executing functions are acceptable. Please refer to the following:

    var demo = function(){
        var innerFunc = function(){
        
        }
        innerFunc();
        return innerFunc;
    }
    
    $(window).resize(function(){
    });

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:44:41

    Does the original poster mean that you want to execute an anonymous function by yourself, and then want to call this anonymous function from another place?

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-16 13:44:41

    There is nothing wrong with the way you write now

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:44:41

    The automatically running js is in the form of (function is written here)(). You can also call it once in the window.onload event

    reply
    0
  • Cancelreply