Function Call and Apply Methods

Function Call and Apply Methods

·

2 min read


call() Method

The call() method accepts an object and optionally argument list.

See the syntax below:

object.method.call(obj1[, arg1, ...argN])

call() method with a parameter object

The call() method is used on an object. The parameter passed to the function is also an object.

See the examples below:

Without call() method.

const person = {
  firstName: "Osagie",
  lastName: "Bello",
  fullName() {
    return `Hello ${this.lastName} ${this.firstName}!`;
  }
};

console.log(person.fullName()); // Hello Bello Osagie!


With call() method.

const person = {
  fullName() {
    return `Hello ${this.lastName} ${this.firstName}!`;
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.call(person1)); Hello Bello Osagie!
console.log(person.fullName.call(person2));  // Hello Richard Jury!

call() method with arguments

The call() method is used on an object with arguments also passed to the function.

const person = {
  fullName(country, city) {
    return `${this.firstName} ${this.lastName}, ${country} ${city}`;
  }
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.call(person1, "Nigeria", "Lagos"));  
// Osagie Bello, Nigeria Lagos
console.log(person.fullName.call(person2, "UK", "Oxford"));  
// Richard Jury, UK Oxford

apply() Method

The apply() method accepts an object and optionally array instead of an argument list.

See the syntax below:

object.method.apply(obj1[, array])

apply() method with arguments array

Not only an object be passed to the apply method, but it also accepts an array.

const person = {
  fullName(country, city) {
    return `${this.firstName} ${this.lastName}, ${country} ${city}`;
  }
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.apply(person1, "Nigeria", "Lagos"));  
// Osagie Bello, Nigeria Lagos
console.log(person.fullName.apply(person2, ["UK", "Oxford"]));  
// Richard Jury, UK Oxford

Happy coding!!!


image.png


image.png