Prototypes & Inheritance in JavaScript - Exercise 2
It is a regular function commonly used with new to create and initialize objects.
function User(name) {
this.name = name;
}
const user = new User('Ava');Define them on the constructor's prototype so instances share one method instead of storing a copy each.
function User(name) { this.name = name; }
User.prototype.greet = function () {
return `Hi, ${this.name}`;
};It creates an object, links it to the constructor's prototype, calls the function with that object as this, and returns the object.
function Product(name) {
this.name = name;
}
const product = new Product('Keyboard');
console.log(Object.getPrototypeOf(product) === Product.prototype);Link the child prototype to the parent prototype with Object.create().
function Animal(name) { this.name = name; }
function Dog(name) { Animal.call(this, name); }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;Replacing a prototype loses its default constructor reference, so restore it for accurate introspection and expected prototype behavior.
Dog.prototype.constructor = Dog;
console.log(new Dog('Rex').constructor === Dog); // trueIt checks whether a constructor's prototype appears anywhere in the object's prototype chain.
const dog = new Dog('Rex');
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true