带参数的闭包函数的巧妙应用

通常我们写的闭包函数大概都这样undefined = function(){ alert("a closure") }()一般都是不需要加参数的,确切的说加参数几乎一点用都没有,因为闭包函数是一个匿名的函数;

它的参数是直接跟在函数定义后面的,也就是说能够传递给闭包函数的参数,通常闭包函数自己也能通过可见域访问到。

比如说var x = 10 (function(){ alert(x) })()var x = 10 (function(x){ alert(x) })(x)他们的效果是一样的,你完全没必要添加参数。

但是经过本人的研究,带参数的闭包其实也是非常有用的,有的时候你必须用它才能达到某种目的。

记住是必须,我用这个技巧完成了一个函数。可以看看我的代码,其中包含用例$interface = function (indo) { var func = function (object) { var impl = {}; for (var name in indo) { var method = object[name]; // 萃取出实现接口的函数。 if (typeof(method)=='function' && method.length==indo[name].length) { // javascript高级技巧: 使用闭包来动态创建引用,否则你的method将指向最后一次保存的引用。 impl[name] = function(method){ return function () { return method.apply(object, arguments); } }(method); } } return impl; } return func; } IMessage = $interface({ getMessage : function () {/*返回消息*/}, setMessage : function (msg) {/*设置消息*/} }); X = function () { this.message = 'hello interface!'; } X.prototype.getMessage = function () { alert(1) return this.message; } X.prototype.setMessage = function (msg) { alert(2) this.message = msg; } x = new X(); alert(IMessage(x).getMessage());可以对比一下不用参数闭包函数的结果 <script>$interface = function (indo) { var func = function (object) { var impl = {}; for (var name in indo) { var method = object[name]; if (typeof(method)=='function' && method.length==indo[name].length) { impl[name] = function(){ return method.apply(object, arguments); } }; } } return impl; } return func; } IMessage = $interface({ getMessage : function () {/*返回消息*/}, setMessage : function (msg) {/*设置消息*/} }); X = function () { this.message = 'hello interface!'; } X.prototype.getMessage = function () { alert(1) return this.message; } X.prototype.setMessage = function (msg) { alert(2) this.message = msg; } x = new X(); alert(IMessage(x).getMessage());</script>运行的结果很出意料之外。

另外我也尝试过 <script>$interface = function (indo) { var func = function (object) { var impl = {}; for (var name in indo) { var method = object[name]; if (typeof(method)=='function' && method.length==indo[name].length) { impl[name] = function () { var m = method; function(){ return m.apply(object, arguments); } } (); } } return impl; } return func; } IMessage = $interface({ getMessage : function () {/*返回消息*/}, setMessage : function (msg) {/*设置消息*/} }); X = function () { this.message = 'hello interface!'; } X.prototype.getMessage = function () { alert(1) return this.message; } X.prototype.setMessage = function (msg) { alert(2) this.message = msg; } x = new X(); alert(IMessage(x).getMessage()); </script>结果依然是想象不到。

照理说每次执行var 语句的话,会产生新的引用变量。

但是似乎js engine里的闭包函数对外部变量的引用并不是引用外部变量的引用。

而是引用外部变量的标识。