-
-
Save zhoumengkang/7871999 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 朋友分享的闭包的坑,我保存一份学习 | |
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
看了半天,没看懂。