How to Separate Behavior from Data in Object-Oriented JavaScript?

Estimated read time 1 min read

In object-oriented JavaScript, you can separate behavior from data by using object constructors to create instances of objects with their own unique properties, and then adding methods to the constructor’s prototype to define their behavior.

Example:

// constructor
function Person(name, age) {
  this.name = name;
  this.age = age;
}

// add behavior to prototype
Person.prototype.greet = function() {
  console.log(`Hello, I am ${this.name} and I am ${this.age} years old.`);
};

// create instances of Person object
const person1 = new Person("John Doe", 30);
const person2 = new Person("Jane Doe", 25);

// call greet method on instances
person1.greet();  // "Hello, I am John Doe and I am 30 years old."
person2.greet();  // "Hello, I am Jane Doe and I am 25 years old."

This way, each instance of the Person object has its own unique data (name and age), while the behavior (the greet method) is shared among all instances via the prototype.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply