When an object lacks a requested property, JavaScript can continue the search through its prototype and that prototype’s prototype. This linked sequence is the prototype chain. section 7.5
The chain makes inherited access different from copying:
- Setting a Ninja prototype to a Person instance links their prototypes, giving Ninja instances access to properties such as Person’s dance method. section 7.3
- instanceof checks whether the right-side function’s prototype occurs in the left-side object’s chain. Changing that function’s prototype can change the result. section 7.3.2
Listing 7.8. Achieving inheritance with prototypes
function Person(){}
Person.prototype.dance = function(){};
function Ninja(){}
Ninja.prototype = new Person(); #A
const ninja = new Ninja();
assert(ninja instanceof Ninja,
"ninja receives functionality from the Ninja prototype");
assert(ninja instanceof Person, "... and the Person prototype");
assert(ninja instanceof Object, "... and the Object prototype");
assert(typeof ninja.dance === "function", "... and can dance!")
Trace how assigning a Person instance as Ninja.prototype lets a Ninja instance pass both instanceof checks and call dance. section 7.3
