Pure prototype inheritance with Object.create

Say I want a bunch of robots to have a common base. They should all have some kind of common base attributes and functionalities. Specifically, their names should be ‘default’, and they should be able to greet people.

Hence, we’ll first create an object with those commonalities first:

Now let’s create a robot that inherits from our object.

if you were to log robotA, you’ll see that its own object is empty. However, its prototype object (__proto__) is that of our robot object. Thus, letting us be able to use those functionalities


{}
__proto__:
greet: ƒ ()
model: "Default"
serial: "000000000"
__proto__: Object

We can do robotA.greet() and we’ll get


"hello, my name is: Default 000000000"

Additionally, you can over those properties and methods in your prototype object. In our case, we can over-ride the firstName and lastName properties to name our robot-like so:


"hello, my name is: R2 D2 3000, 294SFW939sS"

Object.create

Polyfill

Polyfill is code that adds a feature, which certain engines lack. For example, older browsers have older JS engines. They may not support certain functionalities.