Closure Example Relating to 'this' Execution Context


/ Published in: JavaScript
Save to your folder(s)

Example showing how using 'this' in a function depends on where 'this' is defined. From book jQuery in Action.


Copy this code and paste it in your HTML
  1. $(function(){
  2. //Let ID equal a string
  3. this.id = 'someID';
  4. //Set function outer to this
  5. var outer = this;
  6. $('*').each(function(){
  7. /**
  8.   * Since outer is being pulled in from outside the function, it still
  9.   * retains the external context to this. Alert will be 'someID'
  10.   */
  11. alert(outer.id);
  12. });
  13. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.