Home  >  Q&A  >  body text

javascript - The method of mounting to window cannot be executed?

window.aaa = (function($) {
    var bbb = (function() {
      alert(1);
    })();
})(Zepto);

This is an encapsulated script. But how to call bbb outside?

aaa is mounted on the window, but aaa.bbb() cannot be executed

大家讲道理大家讲道理2686 days ago591

reply all(2)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:16:29

    You understand the timely function wrong:

                1、(function(){})();即时函数,会执行一遍;
                    注:window.aaa = (function($) {
                        })(Zepto);
                       你这里的 window.aaa是没有用的 是undefined;
                       你里面的bbb函数也是一样,
                       
                      你外面当然访问不到呀!

    Although I don’t quite understand how you want to call it, it seems that your aaa is mounted in the window, but aaa.bbb() cannot execute this sentence. Then you can change it to:

    window.aaa = (function($) {
    
        var bbb = (function() {
            alert(1);
        });
        return {bbb:bbb};
    })(Zepto);

    You can use aaa.bbb() outside; if you write it like this, you have to pay attention to the closure and variable scope issues in the bbb method~!

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-19 10:16:29

    Use module.export to expose it and require it outside.

    reply
    0
  • Cancelreply