Return to Snippet

Revision: 5382
at March 5, 2008 17:40 by 1man


Initial Code
//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)

Initial URL

                                

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

Initial Title
Function invocation and 'this' Context Example

Initial Tags
function

Initial Language
JavaScript