var eatFunction = function (what_to_eat) {
var sentence = 'I am going to eat a ' + what_to_eat;
console.log( sentence );
};
eatFunction( 'sandwich' );
// is the same as
(function (what_to_eat) {
var sentence = 'I am going to eat a ' + what_to_eat;
console.log(sentence);
})('sandwich');
// is the same as
(function (what_to_eat) {
var sentence = 'I am going to eat a ' + what_to_eat;
console.log(sentence);
}('sandwich'));
// Three of them output 'I am going to eat a sandwich'
唯一的区别是,变量 eatFunction 被移除了,使用一对括号把函数定义包了起来。
示例:
自执行匿名函数
var counter = (function() {
var count = 0;
var get = function() {
count++;
return count;
}
return get;
})();
console.log(counter()); //输出 1
console.log(counter()); //输出 3
console.log(counter()); //输出 3
普通函数
var generateClosure = function() {
var count = 0;
var get = function() {
count++;
return count;
}
return get;
};
var counter = generateClosure();
console.log(counter()); //输出 1
console.log(counter()); //输出 3
console.log(counter()); //输出 3