Skip to content

Latest commit

 

History

History
55 lines (34 loc) · 1.96 KB

# JavaScript Function Invocation Methods.md

File metadata and controls

55 lines (34 loc) · 1.96 KB

JavaScript Function Invocation Methods: call, apply, and bind

Introduction

In JavaScript, functions can be invoked in different ways. The most common way is to simply call the function with the desired arguments. However, there are three other methods that can be used to invoke functions: call(), apply(), and bind(). These methods allow you to control the context in which a function is executed, and they can be useful for a variety of purposes.

Function Invocation Methods

1. The call() Method

The call() method allows you to specify the context in which a function is executed. The first argument to call() is the context object, and the remaining arguments are the arguments that will be passed to the function.

For example, the following code uses the call() method to invoke the newf() function with the obj object as the context object:

function newf(val1, val2, val3) {
  console.log(this.age, val1, val2, val3);
}

var obj = {
  age: 24,
};

newf.call(obj, 1, 2, 3);

This code will output the following to the console:

24 1 2 3

As you can see, the this keyword inside the newf() function refers to the obj object, which is the context object that was specified in the call() method.

2. The apply() Method

The apply() method is similar to the call() method, but it takes an array of arguments instead of individual arguments. The first argument to apply() is the context object, and the second argument is an array of arguments that will be passed to the function.

For example, the following code uses the apply() method to invoke the newf() function with the obj object as the context object and the [1, 2, 3] array as the arguments:

newf.apply(obj, [1, 2, 3]);

This code will output the same result as the previous example:

24 1 2 3

3. The bind() Method

The bind() method creates a new function that is bound

Generated by BlackboxAI