Skip to content

Instantly share code, notes, and snippets.

@CatTail
Last active December 17, 2015 01:49
Show Gist options
  • Save CatTail/5530845 to your computer and use it in GitHub Desktop.
Save CatTail/5530845 to your computer and use it in GitHub Desktop.
浅谈Javascript闭包
// uuid generator, 通过闭包在当前页面状态产生全局唯一的序列
var uuid = (function(){
var id = 0;
return function () {
return id++;
};
}());
uuid(); // 0
uuid(); // 1
uuid(); // 2 ...
// closure creator; 通过闭包来生成闭包, 开始有趣了
var closure = function (func) {
var scope = {};
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(scope);
return func.apply(this, args);
};
};
// 下面示例使用closure来创建相同功能的uuid函数
var uuid2 = closure(function (scope) {
if (scope.id === undefined) {
return scope.id = 0;
}
return ++scope.id;
});
uuid2(); // 0
uuid2(); // 1
uuid2(); // 2 ...
// 上面提到的closure在项目中是用到的, 下面提到的包装函数也是
// wrap提供不修改原始函数的情况下, 加上额外逻辑代码的功能
// 比如, 使用wrap(commitForm, loginCheck)将表单提交和登录检测分离开来.
/**
* Wrap method with extra functionality.
* Wrapped function's this and arguments environment won't be altered.
* While used for function wrap, this will be empty object.
* call `callback` in wrapper as soon as you want to execute the original function.
*
* @param {Function} wrapped Function being wrapped.
* @param {Function} wrapper
* @param {Object=} thisArg Both wrapped and wrapper function this environment.
*/
var wrap = function (wrapped, wrapper, thisArg) {
var args, thisArg = thisArg || {};
var callback = function () {
return wrapped.apply(thisArg, args);
};
return function () {
args = arguments;
return wrapper.apply(thisArg, [callback].concat(Array.prototype.slice.call(args)));
};
};
@CatTail
Copy link
Author

CatTail commented May 7, 2013

第二个函数并不是真正意义上的使用闭包来创建闭包, 只能算是借用闭包或者说---闭包生成器

@ibigbug
Copy link

ibigbug commented May 7, 2013

context玩得飞起啊。。看来我对闭包的理解太狭隘了。。

不过这样wrap之后,跟先后执行两个方法有什么好处呢。。?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment