[removed] global scope

前端 未结 4 646
一个人的身影
一个人的身影 2021-02-03 12:15

Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That\'s working but I want to know what\'s the best way (good practices) to insert js i

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-03 12:56

    You could wrap them in an anonymous function like:

    (function(){ /* */ })();

    However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:

    var mySingleGlobalObject={};
    mySingleGlobalObject.someVariable='a string value';
    mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };
    

    or the alternative, shorter syntax (which does the same thing):

    var mySingleGlobalObject={
      someVariable:'a string value',
      someMethod:function(par1, par2){ /* */ }
    };

    This can then be accessed later from other scripts like:

    mySingleGlobalObject.someMethod('jack', 'jill');

提交回复
热议问题