Skip to content

Instantly share code, notes, and snippets.

@zhoumengkang
Forked from redbluish/closure_caveat.js
Last active December 30, 2015 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhoumengkang/7871999 to your computer and use it in GitHub Desktop.
Save zhoumengkang/7871999 to your computer and use it in GitHub Desktop.
// 朋友分享的闭包的坑,我保存一份学习
// closure caveat
// case 1
;(function (window, $, undefined) {
var $target;
function howdy() {
var x = 'foo';
if (!$target) {
$target = $({})
.on('whatever', function () {
console.log(x);
})
.on('soga', function () {
x = 'bar';
});
$target.triggerHandler('soga');
}
$target.triggerHandler('whatever');
}
howdy();
howdy();
})(this, jQuery);
// case 2
;(function (window, $, undefined) {
var $target, x;
function howdy() {
x = 'foo';
if (!$target) {
$target = $({})
.on('whatever', function () {
console.log(x);
})
.on('soga', function () {
x = 'bar';
});
$target.triggerHandler('soga');
}
$target.triggerHandler('whatever');
}
howdy();
howdy();
})(this, jQuery);
// case 3
;(function (window, $, undefined) {
var $target;
function howdy() {
var x = 'foo';
if (!$target) {
$target = $({}).on('soga', function () {
x = 'bar';
});
}
$target
.off('whatever')
.on('whatever', function () {
console.log(x);
});
$target.triggerHandler('soga');
$target.triggerHandler('whatever');
}
howdy();
howdy();
})(this, jQuery);
// case 4
;(function (window, $, undefined) {
var $target, x;
function howdy() {
x = 'foo';
if (!$target) {
$target = $({}).on('soga', function () {
x = 'bar';
});
}
$target
.off('whatever')
.on('whatever', function () {
console.log(x);
});
$target.triggerHandler('soga');
$target.triggerHandler('whatever');
}
howdy();
howdy();
})(this, jQuery);
@zhoumengkang
Copy link
Author

看了半天,没看懂。

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