理解闭包和匿名

(function(what_to_eat){
        var sentence = 'I am going to eat a ' + what_to_eat;
        console.log(sentence);
})('sandwich');

/*这不是闭包 , 只是简单的匿名函数*/
/*相当于一个匿名函数赋值*/
/*在调用*/
var eatFunction = function(what_to_eat){
        var sentence = 'I am going to eat a ' + what_to_eat;
        console.log(sentence);
}
eatFunction('sandwich');
/*自执行匿名函数的方法*/
	var persion = (function(){
		return "Mike is in prison";
	})();


	/*与下面的语法一致*/
	function makePrison(){
		return 'Mike is in prision';
	}
	var persion2 = makePrison();/*persion2 就是对象的API*/
var menu,outer_function,food = 'cake';
outer_function = function(){
        var fruit ,inner_function;
        fruit = 'apple';
        inner_function = function(){
                return {food:food,fruit:fruit};
        }
        return inner_function;
}
menu = outer_function();
menu();
/*out_function,创建一个执行环境。在这个执行环境中定义了inner_function,
out_function执行环境里面定义inner_function*/
/*inner_function的引用保存到全局作用域,垃圾回收机制阻止垃圾回收器来移除它们。这就是闭包*/

欢迎分享本文,转载请保留出处:前端ABC » 理解闭包和匿名

赞 (2)
分享到:更多 ()

发表评论 0