JavaScript中的(function(){})构造是什么?
我以前知道这意味着什么,但现在我在挣扎 这基本上是说JavaScript中的(function(){})构造是什么?,javascript,iife,Javascript,Iife,我以前知道这意味着什么,但现在我在挣扎 这基本上是说document.onload (function () { })(); 这是一个,或者简称。它在创建后立即执行 它与任何事件(如document.onload)的任何事件处理程序无关。 考虑第一对括号中的部分:(函数){});(…它是一个正则函数表达式。然后看最后一对(function(){})(),这通常添加到表达式中以调用函数;在这种情况下,我们前面的表达式 当试图避免污染全局名称空间时,通常会使用此模式,因为IIFE中使用的所有变量
document.onload
(function () {
})();
这是一个,或者简称。它在创建后立即执行
它与任何事件(如document.onload
)的任何事件处理程序无关。考虑第一对括号中的部分:<代码>(函数){});(<)代码>…它是一个正则函数表达式。然后看最后一对
(function(){})()代码>,这通常添加到表达式中以调用函数;在这种情况下,我们前面的表达式
当试图避免污染全局名称空间时,通常会使用此模式,因为IIFE中使用的所有变量(与任何其他普通函数一样)在其范围之外都不可见。
这就是为什么您可能会将此构造与window.onload
的事件处理程序混淆,因为它通常被用作:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
更正建议人:
函数在创建后立即执行,而不是在解析后执行。在执行脚本块中的任何代码之前,都会对整个脚本块进行解析。此外,解析代码并不自动意味着它已被执行,例如,如果IIFE在函数中,则在调用函数之前它不会被执行
更新
因为这是一个非常流行的话题,值得一提的是,iLife也可以用(如已指出的)来编写:
这是一个,或者简称。它在创建后立即执行
它与任何事件(如document.onload
)的任何事件处理程序无关。
考虑第一对括号中的部分:<代码>(函数){});(<)代码>…它是一个正则函数表达式。然后看最后一对(function(){})()代码>,这通常添加到表达式中以调用函数;在这种情况下,我们前面的表达式
当试图避免污染全局名称空间时,通常会使用此模式,因为IIFE中使用的所有变量(与任何其他普通函数一样)在其范围之外都不可见。
这就是为什么您可能会将此构造与window.onload
的事件处理程序混淆,因为它通常被用作:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
更正建议人:
函数在创建后立即执行,而不是在解析后执行。在执行脚本块中的任何代码之前,都会对整个脚本块进行解析。此外,解析代码并不自动意味着它已被执行,例如,如果IIFE在函数中,则在调用函数之前它不会被执行
更新
因为这是一个非常流行的话题,值得一提的是,iLife也可以用(如已指出的)来编写:
也就是说,立即执行
因此,如果我这样做:
var val = (function(){
var a = 0; // in the scope of this function
return function(x){
a += x;
return a;
};
})();
alert(val(10)); //10
alert(val(11)); //21
小提琴:
第二个例子:
也就是说,立即执行
因此,如果我这样做:
var val = (function(){
var a = 0; // in the scope of this function
return function(x){
a += x;
return a;
};
})();
alert(val(10)); //10
alert(val(11)); //21
小提琴:
第二个例子:
它声明一个匿名函数,然后调用它:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
它声明一个匿名函数,然后调用它:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
这是一个自调用匿名函数
看看这本书
函数表达式可以设置为“自调用”
自动调用(启动)自调用表达式,无需
被召唤
如果表达式为空,函数表达式将自动执行
后跟()
不能自调用函数声明
这是一个自调用匿名函数
看看这本书
函数表达式可以设置为“自调用”
自动调用(启动)自调用表达式,无需
被召唤
如果表达式为空,函数表达式将自动执行
后跟()
不能自调用函数声明
不,这个构造只是创建了一个命名范围。如果你把它分成几个部分,你可以看到你有一个外部的
(...)();
这是一个函数调用。括号内有:
function() {}
这是一个匿名函数。在构造中使用var声明的所有内容将仅在同一构造中可见,并且不会污染全局命名空间。否,此构造只创建一个命名范围。如果你把它分成几个部分,你可以看到你有一个外部的
(...)();
这是一个函数调用。括号内有:
function() {}
这是一个匿名函数。在构造中使用var声明的所有内容将仅在同一构造中可见,并且不会污染全局命名空间。自动执行匿名函数。它一创建就执行
下面是一个简短的虚拟示例,其中该示例非常有用:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
函数准备列表(el){
变量列表=(函数(){
var l=[];
对于(变量i=0;i<9;i++){
l、 推(i);
}
返回l;
})();
返回函数(el){
for(变量i=0,l=list.length;i
因此,不是每次创建一个列表,而是只创建一次(减少开销)。自动执行匿名函数。它一创建就执行
下面是一个简短的虚拟示例,其中该示例非常有用:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
函数准备列表(el){
变量列表=(函数(){
var l=[];
对于(变量i=0;i<9;i++){
l、 推(i);
}
返回l;
})();
返回函数(el){
for(变量i=0,l=list.length;i
因此,不是每次创建一个列表,而是只创建一次(减少开销)。这只是一个匿名函数
2
1
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
(function(obj){
// Do something with this obj
})(object);
var app = window.app || (window.app = {});
console.log(app);
console.log(window.app);
Object {}
Object {}
(function () {
})();
(function (globalObj) {
//Access the globalObj
})(window);
var calculate = (function() {
var cache = {};
return function(a) {
if (cache[a]) {
return cache[a];
} else {
// Calculate heavy operation
cache[a] = heavyOperation(a);
return cache[a];
}
}
})();
(function () {
var count = 10;
})();
console.log(count); // Reference Error: count is not defined
{
let count = 10;
}
console.log(count); // ReferenceError: count is not defined
(function(){
console.log("Hello Stackoverflow!");
})();
var b = 'bee';
console.log(b); // global
function a() {
var b = 'bee';
console.log(b);
}
a();
console.log(b); // ReferenceError: b is not defined -- *as desired*
function a() {
var b = 'bee';
console.log(b);
}(); // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'
(function a() {
var b = 'bee';
console.log(b);
})(); // OK now
(function () { // no name required
var b = 'bee';
console.log(b);
})();
(function() {
// all your code here
// ...
})();
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
a = 10
output = 10
(1+3)
output = 4
// Function Expression
var greet = function(name){
return 'Namaste' + ' ' + name;
}
greet('Santosh');
// IIFE
var greeting = function(name) {
return 'Namaste' + ' ' + name;
}('Santosh')
console.log(greeting) // Namaste Santosh.
// IIFE
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
// test1.js
var greeting = 'Hello';
// iife.js
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
console.log(greeting) // No collision happens here. It prints 'Hello'.
(function () {
})();
// declaration:
function declaredFunction () {}
// expressions:
// storing function into variable
const expressedFunction = function () {}
// Using () operator, which transforms the function into an expression
(function () {})
(function () {
function Question(q,a,c) {
this.q = q;
this.a = a;
this.c = c;
}
Question.prototype.displayQuestion = function() {
console.log(this.q);
for (var i = 0; i < this.a.length; i++) {
console.log(i+": "+this.a[i]);
}
}
Question.prototype.checkAnswer = function(ans) {
if (ans===this.c) {
console.log("correct");
} else {
console.log("incorrect");
}
}
var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);
var questions = [q1, q2, q3];
var n = Math.floor(Math.random() * questions.length)
var answer = parseInt(prompt(questions[n].displayQuestion()));
questions[n].checkAnswer(answer);
})();
// simple
const simpleNumber = (() => {
return true ? 1 : 2
})()
// with param
const isPositiveNumber = ((number) => {
return number > 0 ? true : false
})(4)
function add (a, b){
return a+b;
}
add(5,5);
(function add (a, b){
return a+b;
})
//add(5,5);
(function add (a, b){
return a+b;
})(5,5);
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
const document = "hi there";
console.log(document);
</script>
</body>
<body>
<div id = 'demo'></div>
<script>
(function(){
const document = "hi there";
this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
console.log(document);
})();
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
</script>
</body>
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
calculator = "scientific calculator";
console.log(calculator.mul(5,5));
</script>
</body>
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
var cal = (function(){
var calculator = {
sub:function(a,b){
return a-b;
},
div:function(a,b){
return a/b;
}
}
console.log(this.calculator.mul(5,10));
console.log(calculator.sub(10,5));
return calculator;
})();
console.log(calculator.add(5,10));
console.log(cal.div(10,5));
</script>
</body>
(function(param){
//code here
})(args);
void function(param){
//code here
}(args);