Posted By

1man on 03/05/08


Tagged

this function invocation


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wbowers


Function invocation and 'this' Context Example


 / Published in: JavaScript
 

Quick example to show how 'this' depends on how the function in which you called it in was being invoked. From jQuery in Action.

  1. //Define our objects
  2. var o1 = {handle:'o1'};
  3. var o2 = {handle:'o2'};
  4. var o3 = {handle:'o3'};
  5. //Set handle to window
  6. window.handle = 'window';
  7.  
  8. function whoAmI() {
  9. return this.handle;
  10. }
  11. //Create method in object 01
  12. o1.identifyMe = whoAmI;
  13.  
  14. alert(whoAmI()); //Alerts 'window'
  15. alert(o1.identifyMe()); //Alerts 'o1'
  16. alert(whoAmI.call(o2)); //Alerts 'o2' (call is running whoAmI in the context of o2)
  17. alert(whoAmI.apply(o3)); //Alerts 'o3' (apply is running whoAmI in the context of o3)

Report this snippet  

You need to login to post a comment.