JAVA SCRIPT - Using an Anonymous Function to Wrap Global Variables - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Using an Anonymous Function to Wrap Global Variables - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, December 26, 2018

JAVA SCRIPT - Using an Anonymous Function to Wrap Global Variables

Using an Anonymous Function to Wrap Global Variables


Problem

You need to create a variable that maintains state between function calls, but you want to avoid global variables. 

Solution

Use an Immediately-Invoked Function Expression (IIFE) to wrap variables and functions both:

<!DOCTYPE html>
<head>
<title>faux Global</title>
<script>
 (function() {
 var i = 0;
 function increment() {
 i++;
 alert("value is " + i);
 }
 function runIncrement() {
 while (i < 5) {
 increment();
 }
 }
 window.onload=function() {
 runIncrement();
 }
 })();
</script>
</head>
<body>
</body>
</html>

EXPLAIN

An anonymous function surrounds the global values, is immediately evaluated, and then never evaluated again. Ben Allam gave the pattern the name of ImmediatelyInvoked Function Expression (IIFE or “iffy”), though functionality demonstrated in the solution has existed for some time. IIFEs are used in many major libraries and frame‐ works, including the popular jQuery, as a way of wrapping plug-in functions so that the code can use the jQuery dollar sign function ($) when the jQuery plug-in is used with another framework library. The approach consists of surrounding the code block with parentheses, beginning with the anonymous function syntax, and following up with the code block and then the final function closure. It could be the following, if there’s no parameter passed into the code block:


})();

or the following, if you are passing a parameter into the function:

})(jQuery);

Now you can create as many variables as you need without polluting the global space or colliding with global variables used in other libraries.

1 comment:

  1. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. 金融作业代写

    ReplyDelete

Post Top Ad