Skip to content

Instantly share code, notes, and snippets.

@czheo
Last active April 14, 2018 11:08
Show Gist options
  • Save czheo/04f798f7b6d588dda1b1 to your computer and use it in GitHub Desktop.
Save czheo/04f798f7b6d588dda1b1 to your computer and use it in GitHub Desktop.
Javascript Tips: 10 Things I Learned from the jQuery Source http://www.youtube.com/watch?v=i_qE1iAmjFg
/* self invoking anon function */
// you may see a wrapper like this
(function (window, document, undefined) {
// code here
})(this, this.document);
/*********** Break Down ************/
// this function invoke itself
(function(){
// code here
})();
// alternative style 1
!function(){
// code here
}()
// alternative style 2
+function(){
// code here
}()
/*********** Why it's good ************/
// when the code is minified, it would become something like:
(function(A, B, C){
// all window, document, undefined in the code will be replaced by A, B, C
})(this, this.document)
/* async recursion */
/*******************************************/
// use the pattern above, we can do asynchronous recursion
// setInterval is evil! Never use it!
setInterval(function(){
// setInterval may keep running, even if your code breaks here
}, 1000);
// if you don't believe, try code below in your js developer tool
setInterval(function(){ JERKY_CODE_HERE }, 1000);
/************ do this instead **************/
(function(){
// your code here
setTimeout(arguments.callee, 1000)
})();
// if you want know more about what arguments.callee is,
// check out here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee
/*******************************************/
// because arguments.callee will be forbidden in the strict mode of ECMAScript 5, you can get around it by giving a name to the function
(function loopsiloopsiloo(){
// your code here
setTimeout(loopsiloopsiloo, 1000)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment