0

I am writing a new js file and I want to wrap my function to make sure that I am safeguarding it to collide with any other functions in other js files. The issue that I am confused about is that I am using this:

var myVariable = (function (p1, p2) {

  });

because I want to be able to invoke that method later on sometime by calling the variable. The above works just fine. However you can see that myVariable is not encapsulated. When I try to do this:

(var myVariable = function (p1, p2) {

  });

that does not work. My question is how do I encapsulate that function so I can use it later?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221
  • 3
    Are you trying to encapsulate a function so much that even _you_ can't use it? If not, I'd wrap it in some sort of ["namespace"](http://stackoverflow.com/a/881556/5601284), or look at [IIFEs](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) _(Immediately Invoked Function Expressions)_ – byxor Nov 02 '16 at 20:29
  • You don't need to wrap the function in `()` - if you simply do `var myVariable = function( /* args */) { /* code */}` you'll be able to access `myVariable` (assuming it's global) but everything inside the function will be scoped to being inside it. – VLAZ Nov 02 '16 at 20:29
  • What does the full function this code belongs to look like? – Amy Blankenship Nov 02 '16 at 20:32
  • 2
    You can't both wrap your code to make sure it doesn't interfere, and at the same time have it globally accessible. Best case is that you create a single variable that doesn't clash with anything, and just chain everything onto that as properties, and then wrap the code in an IIFE returning the single variable. – adeneo Nov 02 '16 at 20:34
  • ok so the way I am doing is correct then. – Asim Zaidi Nov 02 '16 at 20:34
  • Are you trying to write a global helper function with AngularJS ? – Zakaria Nov 02 '16 at 21:14
  • 1
    JS modules (CommonJS, AMD, ES6, whatever) are actually supposed to serve this purpose. In the case of non-modular environment exposing something for reuse means polluting global scope. If the variable is used within single file, IIFE may be used as a workaround. – Estus Flask Nov 02 '16 at 22:40

0 Answers0