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); // true

It 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
this.value = 0; this.reset = () => { this.value = 0; }; // own method } Counter.prototype.increment = function () { this.value += 1; }; const counter = new Counter();

Class 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); // true