Function invocation and 'this' Context Example


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

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.