Javascript Function - Call and Apply (Examples)

Tech:
Javascript
Since:
1 year ago
Views:
2

Function is a block of code that performs a set of operations. It has two methods, call and apply. Here is an example of how to use call and apply.

function

Function is defined with the keyword function followed by the name of the function. The code block in curly braces is the body of the function and is executed when the function is called using the function name. The self-invoking function is used to create a function on the fly, without having to call it. The arrow funtion is a shorter way to write the function which is introduced in ES6.

function fn_name(parameters) {
  // Code
}

// SELF INOVOKING
(function() {
  // Code
})();

// ARROW FUNCTION
fn_name = () => {
  // Code
};

call

It is a method that can be used on different objects. The call method is used to invoke a function with a given this value and arguments provided individually.

var obj1 = {
  TEST: function(a, b) {
    return a + b + this.xxx + this.yyy;
  }
};
var obj2 = {
  xxx: "xxx",
  yyy: "yyy"
};
obj1.TEST.call(obj2, "aaa", "bbb");

apply

It is a method that can be used on different objects. The apply method is used to invoke a function with a given this value and arguments provided as an array.

var obj1 = {
  TEST: function(a, b) {
    return a + b + this.xxx + this.yyy;
  }
};
var obj2 = {
  xxx: "xxx",
  yyy: "yyy"
};
obj1.TEST.apply(obj2, ["aaa", "bbb"]);