Chapter 6 - Objects

6.1.4 Object create

by Denise Nepraunig

JavaScript

// JavaScript The Definitive Guide 6th Edition
// 6.1.4 Object.create

// Object.create creates an object, which uses the first argument
// as a prototpye of tat object.

// Object.create also takes an optional second parameter
// that describes the properties of the new object

// Object.create is a static function, not an method invoked
// on individual objects

var o1 = Object.create({x: 1, y: 2}); // o1 inherits x and y

var o2 = Object.create(null); // doesn't inherit anything
// not even stuff like .toString

var o3 = Object.create(Object.prototype); // the same like new Object
// or {}

// here our own inherit function
function inherit(p) {
    if (p == null) throw TypeError();
    if (Object.create)
        return Object.create(p);
    // here polyfill stuff
    var t = typeof p;
    if (t !== "object" && t !== "function") throw TypeError();
    function f() {}; // dummy constructor
    f.prototpye = p; // set prototype
    return new f(); // use f() to create an 'heir' of p (Erben)
}

// with this inherit functio we can 'guard' our object against
// accidental modifications --> we send a heir and not our object

function library_function(obj) {
    // muahahaha I can have control over you!!!
    obj.x = "Take this you object!";
    console.log(obj.x);
}

var o = { x: "don't change this value" };
library_function(inherit(o));
console.log(o);