Hello, my name is: Amy

Explain how prototypal inheritance works

A plain old javaScript object, var obj = new Object(); actually comes with a lot more than just a blank object (obj = {};). If you were to console out obj you would see that this seemingly blank object comes with a few methods that are inherent to objects (hasOwnProperty, isPrototypeOf, toString, etc). This is what is referred to as the objects prototype.

The useful thing about this, though, is that if I were to create a new object off of my original obj it will inherit the original methods/properties of that object.

Using vehicles works best for my brain:

var vehicle = new Object();

Here we already have access to the native methods for objects. Let's add some this that all vehicles will most likely need.

vehicle.move = function(current) {
  return current + 1;
}
vehicle.color = 'blue';

So now our Vehicle object looks like so:

vehicle = {
  move: function(current) {
    return current + 1;
  },
  color: 'blue'
}

If I was to create a new object, based off of this object, it would automatically come with both the properties/methods of vehicle as well as the standard object.

var car = Object.create(vehicle);

console.log(car.color); //blue

Since the property color was not directly present on the object car, javascript then goes back on prototype and looks at the vehicle object to see if there is a property called color. Because there is, it is returned; however if there was not it would continue going backwards until it was back at the origin of the object.

Comments