Skip to content

Instantly share code, notes, and snippets.

@nshathish
Last active June 17, 2017 18:56
Show Gist options
  • Save nshathish/ea786d27a0adbbdf52dc44a5ac593807 to your computer and use it in GitHub Desktop.
Save nshathish/ea786d27a0adbbdf52dc44a5ac593807 to your computer and use it in GitHub Desktop.
var obj = {num: 2};
var addToThis = function(a) {
return this.num + a;
};
addToThis.call(obj, 3); // 5
var addToThis2 = function (a, b, c) {
return this.num + a + b + c;
};
// using the call method
addToThis2.call(obj, 1, 2, 3); // 8
// using the apply method
var args = [1, 2, 3];
addToThis.apply(obj, args); // 8
// bind returns a function
var bound = addToThis2.bind(obj);
bound(1, 2 ,3); // 8
// an example of using call
var obj1 = {
name: "Frank",
greet: function() {
console.log("name: " + this.name);
}
};
var obj2 = {
name: "Andy"
};
obj1.greet.call(obj2); // Andy
// this is equivalent to call obj2.greet(), as if though greet function is defined in obj2
// this idea could be used to convert arguments into an array. arguments is an array like object, but no an array
// so methods like split, shift...etc won't work on arguments
var args = [].split.call(arguments);
/*
call, apply or bind cannot be used with arrow functions
*/
var addThisArrow = x => this.num + x;
addThisArrow.call(obj, 2); // will get an error 'cannot read property "num" of undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment