Created
December 9, 2013 12:46
-
-
Save redbluish/7871760 to your computer and use it in GitHub Desktop.
closure_caveat.js
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
感谢分享,带走,学习.