Javascript prototypes
Created By: chatGPT
JavaScript is a prototype-based programming language, which means it relies on prototypes instead of classes for inheritance. Each object can serve as a prototype for another object. This allows for dynamic extension of objects and reuse of properties and methods across different objects.
Creating an Object Prototype: You can create an object prototype by defining a constructor function and adding properties or methods to the prototype object.
In this example, we created a function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
Person
constructor that initializes name and age. We added a greet
method to Person.prototype
, allowing all instances of Person
to use this method.Instantiating an Object: You can create an instance of the
Person
object and invoke the greet
method as follows.const john = new Person('John', 30);
john.greet(); // Outputs: Hello, my name is John
Inheritance via Prototypes: You can also create a new object that inherits from an existing prototype. For example, you can create a
Here, we use Employee
constructor that inherits from Person
.function Employee(name, age, title) {
Person.call(this, name, age);
this.title = title;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.describe = function() {
console.log(`${this.name} is a ${this.title}`);
};
Object.create
to set up inheritance and preserve the prototype chain. Now, Employee
instances can also use methods from the Person
prototype.Using the Inherited Object: We can instantiate the
Prototype Chain: Remember that JavaScript checks the prototype chain when you access properties. If a property is not found in the object itself, it looks up the prototype chain until it finds the property or reaches the end of the chain.Employee
object and call its methods just like we did with Person
.const jane = new Employee('Jane', 28, 'Developer');
jane.greet(); // Outputs: Hello, my name is Jane
jane.describe(); // Outputs: Jane is a Developer