Object Prototypes

Objectives

  1. Understanding JavaScript object prototypes

  2. Grasping how prototype chains work

  3. Learning how to add new methods on the prototype property

Prototype-based Language?

JavaScript inheritance works a bit differently than other languages.

  • The template object is called a prototype object

  • Prototype object objects can inherit methods and properties from existing prototype objects.

  • The above is more commonly referred to as the prototype chain.

  • When object instances are created in classic OOP, all the defined properties and methods are copied over.

  • In JavaScript, the object instance is linked with its prototype via the _proto_ property. Properties and methods are found as you move up the chain.

An Example

Let's remember how we defined a constructor function:

function Person(first, last, age, gender, interests) {
    // property and method definitions
    this.first = first;
    this.last = last;
//...
}

And we created an object instance:

var person1 = new Person('John', 'Doe', 69, 'male', ['napping', 'Charleston Chews']);

We can actually see the prototype chain at work as soon as we type person1.

  • Let's start by opening the dev tools in your browser. You can do it on any page, just hit ctrl + shift + i. Ignore the errors in this screenshot

  • Next, we'll copy and paste our example code into the window. The code in the screenshot is not everything that is added and incorporates the challenges from the end of the previous section.

  • Hit enter to go to a new line. You'll see something that says undefined, but that's ok.

  • Now comes the fun stuff, type person1. And watch as a bunch of properties fill the screen.

  • You might notice name, age, gender, interests, and bio. These properties are defined on Person(), person1's prototype object.

  • Wait, what are these new things like watch and valueOf? They're actually properties defined on Object, Person()'s prototype object!

  • You can even tell where the properties are defined in the window!

  • We'll talk more about properties in the next module, but you can sort of see how the prototype chain works now!

So the prototype chain looks like this: person1 => Person => Object The double arrows => point to prototype object they inherit from.

Method Calling on the Chain

Say you're trying to call the valueOf() method on person1.

  • Your browser goes along the prototype chain trying to find an object that has the method available on it.

  • It finally calls the method when it reaches Object().

  • Try to call methods on your own in the console window (discuss your findings?).

Last updated