NSS Day 7, navigating the prototype chain
Classical inheritance is for chumps
Conventional object-oriented languages like C++ and Java have classes. JavaScript? Not so much; JavaScript has prototypal inheritance based around functions. These functions, created properly (their names start with capital letters), function similarly to classes.
By similarly to classes, I mean that when used with the “new” statement, they create objects. The similarities end there.
function Person(name){name: name};var person = new Person('Adam');The variable “person” now points to an object in memory with 1 property, “name” which equals ‘Adam’.
This is great, but prototypal inheritance makes it better. Say we create a second person:
var person2 = new Person(‘Jill’);
“person” & “person2" now both point to objects that each have 1 property, name. Say we want our people to be able to say hi. We could add a new property to both objects, but JavaScript allows us to use a much better option:
Person.prototype.sayHi = function(){console.log(this.name + ‘ says hi.’);
}
Now we can call person.sayHi() & person1.sayHi() and get:
> Adam says hi.
> Jill says hi.
Since both person & person1 are instances of Person, they both have access to Person’s prototype object (the place in memory where we added our new .sayHi function).
This is what is meant by the prototype chain. The Person function “owns” the Person.prototype object, and every instance of Person (every object create with “new Person()”) has an internal link to the prototype object.
That link allows each instance to use a shared method by referencing a single function in memory (optimizing memory usage) as well as allows you to add a new property or method to every instance of an object simply by adding it to the object constructor’s prototype object.