Inheritance lets an object reuse properties and behavior from another object instead of duplicating them. In JavaScript, that reuse follows prototypes: if a property is missing on an object, the search continues through its prototype chain. section 7.1
Following the chain
Give one object a prototype that has a `sneak` property, and `"sneak" in object` becomes true. If that prototype has its own prototype with a `creep` property, the first object can access `creep` too. The search stops when there are no more prototypes. section 7.1
Two ways to establish the relationship:
- With constructor functions, assigning `Ninja.prototype = new Person()` puts Person in the prototype chain. Copying `Person.prototype.dance` onto Ninja’s prototype merely copies a method; it does not make Ninja instances instances of Person. This older approach also requires restoring the prototype’s `constructor` property. section 7.3 section 7.4.2
- With ES6 classes, `class Ninja extends Person` expresses the relationship directly. A derived constructor calls `super(name)` to initialize the Person part, then can add its own properties and methods. section 7.4.2
Listing 7.15. Inheritance in ES6
class Person {
constructor(name){
this.name = name;
}
dance(){
return true;
}
}
class Ninja extends Person { #A
constructor(name, weapon){
super(name); #B
this.weapon = weapon;
}
wieldWeapon(){
return true;
}
}
var person = new Person("Bob");
assert(person instanceof Person, "A person's a person");
assert(person.dance(), "A person can dance.");
assert(person.name === "Bob", "We can call it by name.");
assert(!(person instanceof Ninja), "But it's not a Ninja");
assert(!("wieldWeapon" in person), "And it cannot wield a weapon");
var ninja = new Ninja("Yoshi", "Wakizashi");
assert(ninja instanceof Ninja, "A ninja's a ninja");
assert(ninja.wieldWeapon(), "That can wield a weapon");
assert(ninja instanceof Person, "But it's also a person");
assert(ninja.name === "Yoshi" , "That has a name");
assert(ninja.dance(), "And enjoys dancing");
Compare the two instances: a Person can dance but cannot wield a weapon; a Ninja can wield a weapon and also has Person’s name and dance method. section 7.4.2


















