Created
April 25, 2017 08:16
-
-
Save shahbazsyed/2c5849743b3bbdb247121f6a8b1eb2c1 to your computer and use it in GitHub Desktop.
JS call, apply ,bind
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
// Consider an object having a num property | |
var obj = {num:2}; | |
// Note the use of this in the function | |
var addToThis = function(a,b,c){ | |
return this.num + a+b+c; | |
}; | |
// call is used to call a function on an object with the arguments passed along | |
var result = addToThis.call(obj,4,3,4); // functioname.call(object_to_be_called, arguments_to_function) | |
console.log(result); // 13 | |
var array=[4,3,4]; | |
// apply is similar to call, except that it takes an array of arguments instead of comma separated values | |
console.log(addToThis.apply(obj,array)); // 13 | |
// bind returns a function whose this property points to the passed object, which can then be called using a comma separated list of arguments | |
console.log(addToThis.bind(obj)(4,3,4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment