javascript - Difference between IIFE and regular function (example) - Stack Overflow

Learning about IIFEs i understand that using them does:not pollute the global scopeshields your code f

Learning about IIFEs i understand that using them does:

  • not pollute the global scope
  • shields your code from others.

Could someone please help me understand it better and give a real example of when i could get in trouble when using regular function statement (instead od IIFE?)

Learning about IIFEs i understand that using them does:

  • not pollute the global scope
  • shields your code from others.

Could someone please help me understand it better and give a real example of when i could get in trouble when using regular function statement (instead od IIFE?)

Share Improve this question edited Feb 5, 2020 at 5:43 bartc asked Feb 5, 2020 at 5:40 bartcbartc 1331 silver badge12 bronze badges 2
  • You mean IIFE: Immediately Invoked Function Expression? – Nishant Commented Feb 5, 2020 at 5:43
  • Outside of the modules, (almost) every script should be closed inside an IIFE. – Teemu Commented Feb 5, 2020 at 5:46
Add a ment  | 

3 Answers 3

Reset to default 7

Let's say you have a decent sized codebase (a few thousand lines or more). Putting every function on the top level won't be a good idea, because then it'll be pretty easy to accidentally write a function name twice, which will cause bugs due to the name collision. For example:

// code around validating user registration
function validate(username) {
  return /someValidationRegex/.test(username);
}
// do stuff with validate


// And then, far elsewhere in the code,
// you need to validate an input for sending to the server:
function validate(input) {
  return /someOtherValidationRegex/.test(input);
}
// do stuff with validate

This will not work, because the last validate function will overwrite the first validate function, and the code won't work as expected.

Put each segment of code into an IIFE instead, to avoid the possibility of name collisions:

(() => {
  // code around validating user registration
  function validate(username) {
    return /someValidationRegex/.test(username);
  }
  // do stuff with validate
})();

(() => {
  // code around validating an input for sending to the server:
  function validate(input) {
    return /someOtherValidationRegex/.test(input);
  }
  // do stuff with validate
})();

This is the technique that Stack Overflow's Javascript uses (at least in some parts).

Another reason to use IIFEs even if you're careful not to duplicate function names is that you may accidentally duplicate a window property. For example, the following is a somewhat mon bug people run into:

// name is defined to be a number...
var name = 5;
// but it's actually a string???
console.log(typeof name);

The problem here is that you're accidentally referring to / overwriting the window.name property on the top level, and window.name may only be a string. There are a whole bunch of functions and variables defined on the top level. To avoid name collisions, put everything into an IIFE instead:

(() => {
  // name is defined to be a number...
  var name = 5;
  // And it's still a number, good
  console.log(typeof name);
})();

Still, if your codebase is large enough that name collisions are a decent possibility, rather than manually writing IIFEs, I'd highly remend using a module system instead, like with Webpack. This will allow you to write modules inside their own encapsulated scope, without leakage or name collisions, and will be more maintainable, when each module only contains exactly the code it needs to run, and nothing more. This makes identifying bugs and extending features much easier than one huge long <script> that you have to navigate through manually.

The mon advantage of IIFE is that any "Function or Variable" defined inside IIFE, cannot be accessed outside the IIFE block, thus preventing global scope from getting polluted.

IIFE's are used to define and execute functions on fly and use them on the spot without extra line of Code.

(function(){
  var firstName = 'Jhon';
  console.log(firstName);
})(); // will be executed on the fly

function test(){
  var firstName = 'Jhon';
  console.log(firstName);
}
test(); // has to call manually

The IIFE will actually run (immediately-invoked function expression), they don't need a trigger or function call to initiate them, so the variable will be set to its response.

Here's a Fiddle to demonstrate this:

var iffe = (function() {
    return 'foo';
})();

var func = function() {
    return 'bar';
};

console.log('iife = ' + iffe);
console.log('non-iife = ' + func);

In your JS console you'll see something similar to:

iife = foo and

non-iife = function () { return 'bar'; }

Also in case we need to pass something in the IFFE scope from the outer scope we need to pass them as a parameter and receive this inside the function defined in the IFFE wrap, something like this -:

var iffe = (function(doc) {
    return 'foo';
})(document);

This is a link for some more reference - http://benalman./news/2010/11/immediately-invoked-function-expression/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744407395a4572703.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信