How to Use Prototypes, Call, and Apply in Object-Oriented JavaScript?

Estimated read time 1 min read

Prototypes, call(), and apply() are fundamental concepts in Object-Oriented JavaScript.

  1. Prototypes: Every object in JavaScript has a prototype that serves as a blueprint for creating instances of that object. You can add new properties or methods to the prototype, and they will be available to all instances of the object.
  2. call(): The call() method is used to call a function with a specified this value and arguments. The syntax is:
functionName.call(thisArg, arg1, arg2, ...);
  1. apply(): The apply() method is similar to call() but instead of passing in individual arguments, you pass an array of arguments. The syntax is:
functionName.apply(thisArg, [arg1, arg2, ...]);

Example:

// Example object
let obj = { name: 'John' };

// Example function
function sayHi() {
  console.log(`Hi, I'm ${this.name}`);
}

// Call the function using call()
sayHi.call(obj); // Hi, I'm John

// Call the function using apply()
sayHi.apply(obj); // Hi, I'm John

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply