Monday, February 29, 2016

JavaScript call apply


Call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

var obj = {
  num: 2
};

var addToThis = function(a) {
  return this.num + a;
};

addToThis.call(obj,3);


the obj is passed to addToThis function which has "num" property. a is passed when call is made.


Apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

var addToThis = function(a, b, c) {
  return this.num + a + b+ c;
};

arr = [1,2,3];
console.log(addToThis.apply(obj, arr);

the obj is passed to addToThis function which has "num" property. arguments  is passed in an array when apply is made

No comments:

Post a Comment