Created
May 18, 2020 23:21
-
-
Save Omkaragrawal/c6d8de530cb9d5011938bb3cd07cafb3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An object can be passed as the first argument to call or apply and this will be bound to it. | |
var obj = {a: 'Custom'}; | |
// We declare a variable and the variable is assigned to the global window as its property. | |
var a = 'Global'; | |
function whatsThis() { | |
return this.a; // The value of this is dependent on how the function is called | |
} | |
whatsThis(); // 'Global' as this in the function isn't set, so it defaults to the global/window object/globalThis | |
whatsThis.call(obj); // 'Custom' as this in the function is set to obj | |
whatsThis.apply(obj); // 'Custom' as this in the function is set to obj | |
// .call() and .apply() method example 1 | |
function add(c, d) { | |
return this.a + this.b + c + d; | |
} | |
var o = {a: 1, b: 3}; | |
// The first parameter is the object to use as | |
// 'this', subsequent parameters are passed as | |
// arguments in the function call | |
add.call(o, 5, 7); // 16 | |
// The first parameter is the object to use as | |
// 'this', the second is an array whose | |
// members are used as the arguments in the function call | |
add.apply(o, [10, 20]); // 34 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment