本文共 1547 字,大约阅读时间需要 5 分钟。
(function () { var foo = 10; var bar = 2; console.log(foo*bar);})(); // 20
(function (foo,bar) { console.log(foo*bar);})(10,2); // 20var baz = (function (foo,bar) { return foo * bar;})(10,2);console.log(baz); // 20
var baz;(function () { var foo = 10; var bar = 2; baz = function () { return foo * bar; }})();console.log(baz()); // 20
能理解下面的几个代码块,就算能理解闭包了。闭包可以读取其他函数内部变量。
var that = this;
就是精髓。
// 代码块一var name = "The Window";var object = { name : "My Object", getNameFunc : function(){ return function(){ return this.name; // this是匿名函数 }; }};console.log(object.getNameFunc()()); // undefinedconsole.log(object.getNameFunc().call(object)); // My Object// 代码块二var name = "The Window";var object = { name : "My Object", getNameFunc : function(){ var that = this; return function(){ // 闭包 return that.name; }; }};console.log(object.getNameFunc()()); // My Object// 代码块三var name = "The Window";var object = { name : "My Object", getNameFunc : function(){ return function(){ return name; }; }};console.log(object.getNameFunc()()); // The Window// 代码块四var name = "The Window";var object = { name : "My Object", getNameFunc : function(){ return this.name; // this是object }};console.log(object.getNameFunc()); // My Object
方法论总结:可以针对关键点,进行深入探讨。百度搜索相关的博文或百科探索。
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6197068.html,如需转载请自行联系原作者