Prototype Chaining in JavaScript

Prototype chaining is useful to share properties from one object to another.

Let’s illustrate through code

First we declare our shallowCopy function which is one of the most common ways to copy an object. You can find it in here:

function shallowCopy(orginal) {
    // First create an empty object with
    // same prototype of our original source
    var clone = Object.create(Object.getPrototypeOf(orginal));

    var i, keys = Object.getOwnPropertyNames(orginal);
    for (i = 0; i & lt; keys.length; i += 1) {
        // copy each property into the clone
        Object.defineProperty(clone, keys[i],
            Object.getOwnPropertyDescriptor(orginal, keys[i])
    return clone;

var gold = {a:1};

console.log(gold.a); // 1
console.log(gold.z); // undefined

var blue = shallowCopy(gold); 
blue.b = 2;
console.log(blue.a); // 1
console.log(blue.b); // 2
blue.a = 3;

Another way to create an object out of another is using the built in Object.create
however as you will see it differs from a shallowCopy function a lot. The object.create() function creates an ongoing bound between the new object and the original so new properties that gets added the to the original object gets passed on to the new one.

var rose = Object.create(gold);
rose.b = 2;
console.log(rose.a); //1
console.log(rose.b); //2

gold.z = 9;
console.log(blue.z); // undefined
console.log(rose.z); // 9

it also overwrites the old passed values to an existing property if it’s still the original that’s being used. Though this can be prevented by setting the value explicit to the new object like in this example.

rose.a = 1;
gold.a = 3;
console.log(rose.a); // 1

Without the first line the outcome would have changed to 3 and overwritten the original value.

Add your comment