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);
// 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.');}();
// 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'.
// declaration:function declaredFunction () {}
// expressions:
// storing function into variableconst expressedFunction = function () {}
// Using () operator, which transforms the function into an expression(function () {})
表达式只是一堆可以计算为一个值的代码。对于上面示例中的表达式,此值为单函数对象。
在我们有一个计算为函数对象的表达式后,我们可以立即使用()运算符对函数对象进行调用。例如:
(function() {
const foo = 10; // all variables inside here are scoped to the function blockconsole.log(foo);
})();
console.log(foo); // referenceError foo is scoped to the IIFE
var x;
// Here, fibonacci is a block functionfunction fibonacci(x) {var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);if (x === 9) console.log("The " + x + "th fibonacci is: " + value);return value;}
(x = 9);
console.log("Value of x: " + x);console.log("fibonacci is a(n) " + typeof fibonacci);
观察当我们将函数转换为表达式时,事情是如何变化的。
var x;
// Here, fibonacci is a function expression(function fibonacci(x) {var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);if (x === 9) console.log("The " + x + "th fibonacci is: " + value);return value;})
(x = 9);
console.log("Value of x: " + x);console.log("fibonacci is a(n) " + typeof fibonacci);
当你使用非运算符而不是括号时,也会发生同样的事情,因为两个运算符都将语句转换为表达式:
var x;
// Here, fibonacci is a function expression! function fibonacci(x) {var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);if (x === 9) console.log("The " + x + "th fibonacci is: " + value);return value;}
(x = 9);
console.log("Value of x: " + x);console.log("fibonacci is a(n) " + typeof fibonacci);
function name(parameter1, parameter2, parameter3) {// code to be executed}
函数要执行的代码放在大括号内:{}
演示:-
let x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {return a * b; // Function returns the product of a and b}console.log(x);