Skip to main content

Object Prototypes in JavaScript (Live Playground)

In this tutorial, we will explore object prototypes and inheritance in JavaScript. You will learn how to create custom objects and share methods across instances using prototypes.

Object Prototypes

In JavaScript, every object has a prototype, which is another object that it inherits properties and methods from. When an object is created, its prototype is automatically assigned to the object's constructor's prototype property.

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

const john = new Person('John', 30);
console.log(john); // Output: Person { name: 'John', age: 30 }

In this example, the Person constructor function has a prototype property, and the john object's prototype is the Person.prototype object.

Live Playground, Try it Yourself

Adding Methods to the Prototype

You can add methods to the prototype object so that all instances of a constructor function can access and use these methods.

Person.prototype.sayHello = function () {
console.log('Hello, my name is ' + this.name + '.');
};

john.sayHello(); // Output: Hello, my name is John.

The sayHello method is added to the Person.prototype object, which allows the john object to use it.

Live Playground, Try it Yourself

Prototypal Inheritance

In JavaScript, objects can inherit properties and methods from other objects through prototypal inheritance. When you try to access a property or method on an object that doesn't exist, JavaScript looks up the prototype chain to find the property or method in one of the prototypes.

function Employee(name, age, role) {
Person.call(this, name, age);
this.role = role;
}

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

const jane = new Employee('Jane', 28, 'Software Engineer');
jane.sayHello(); // Output: Hello, my name is Jane.

In this example, the Employee constructor function inherits properties and methods from the Person constructor function. We create a new object with the prototype set to Person.prototype and assign it to Employee.prototype. Then, we set the constructor property back to Employee. This way, jane can use the sayHello method inherited from Person.prototype.

Live Playground, Try it Yourself

Conclusion

Object prototypes and inheritance are essential concepts in JavaScript, allowing you to create custom objects and share methods across instances. By understanding how prototypes work and how to use prototypal inheritance, you can create more efficient and maintainable JavaScript code.