/ 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.
                
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
//Define our objects
var o1 = {handle:'o1'};
var o2 = {handle:'o2'};
var o3 = {handle:'o3'};
//Set handle to window
window.handle = 'window';
function whoAmI() {
return this.handle;
}
//Create method in object 01
o1.identifyMe = whoAmI;
alert(whoAmI()); //Alerts 'window'
alert(o1.identifyMe()); //Alerts 'o1'
alert(whoAmI.call(o2)); //Alerts 'o2' (call is running whoAmI in the context of o2)
alert(whoAmI.apply(o3)); //Alerts 'o3' (apply is running whoAmI in the context of o3)
Comments
 Subscribe to comments
                    Subscribe to comments
                
                