Home >Web Front-end >JS Tutorial >Analysis of the immediate execution function of javascript
This article mainly introduces the analysis of javascript's t immediate execution function. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Concept:
Immediate execution As the name suggests, the function is executed immediately after the function is defined.
Function expression method:
Add parentheses () after the function expression to execute the function immediately.
var xmlhttpUtil = function () { function getText(url,callback){ alert("dog"); }();
Anonymous function method:
Anonymous functions are not allowed to appear directly in javascript as a separate statement, so if you want to execute the function immediately,
must make some grammatical changes: Method 1, It assigns an anonymous function to a variable, which becomes a function expression and can be executed immediately by adding parentheses after it.
Method 2: Put a bracket around the anonymous function (this is allowed by js grammar), which is equivalent to a function expression, and then add brackets after it to execute it immediately.
(function(b){ alert(b); })(321);
Modularization:
Because variables inside the function will not pollute the global scope, immediate execution of functions can be used for modularization. Many third-party libraries have adopted this approach.
var xmlhttpUtil = function () { function getText(url,callback){ var request=new XMLHttpRequest(); request.open("GET",url); request.send(null); request.onreadystatechange=function(){ if(request.readyState===4 && request.status===200){ var type=request.getResponseHeader("Content-Type"); if(type.match(/^text/)) callback(request.responseText); alert(request.responseText); } else { } } } let xmlHttpRequestObj={}; xmlHttpRequestObj.getText=getText; return xmlHttpRequestObj; }();
Execution:
xmlhttpUtil.getText("/dog",function () { alert("xmlhttprequest请求响应!"); });
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Algorithmic ideas for implementing quick sort in JavaScript
Introduction to the principle of new calling function in JS
The above is the detailed content of Analysis of the immediate execution function of javascript. For more information, please follow other related articles on the PHP Chinese website!