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); // trueClass syntax is a clearer layer over the same prototype-based inheritance system; instance methods still live on the class prototype.
class User {
greet() { return 'Hello'; }
}
const user = new User();
console.log(user.greet === User.prototype.greet); // trueCalling the parent constructor with the child instance as this initializes inherited instance properties.
function Animal(name) { this.name = name; }
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
console.log(new Dog('Rex', 'Beagle').name);Define it on the child constructor's prototype so all child instances can share the method.
function Dog(name) { this.name = name; }
Dog.prototype.fetch = function () {
return `${this.name} fetches`;
};
console.log(new Dog('Rex').fetch());JavaScript finds the child's method first, so the child implementation shadows the inherited one.
function Animal() {}
Animal.prototype.speak = function () { return 'sound'; };
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.speak = function () { return 'woof'; };
console.log(new Dog().speak()); // woof