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:
1 2 3 4 5 6 7 |
var robot = { model: 'Default', serial: "000000000", greet: function() { return 'hello, my name is: ' + this.model + ', ' + this.serial; } } |
Now let’s create a robot that inherits from our object.
1 |
var robotA = Object.create(robot); |
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:
1 2 |
robotA.model = "R2 D2 3000"; robotA.serial = "294SFW939sS"; |
"hello, my name is: R2 D2 3000, 294SFW939sS"
Object.create
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Object.create = function(o) { // declare definition function F () { } // have function object F's prototype point to another object F.prototype = o; // thus, when we instantiate, // the new instance's __proto__ will point to object pro return new F(); } |
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.