JavaScript Inheritance Setting an Object's prototype



With ES5+, the Object.create function can be used to create an Object with any other Object as it's prototype.

const anyObj = {
    hello() {
        console.log(` is ${}`);

let objWithProto = Object.create(anyObj); = 'bar';

objWithProto.hello(); // " is bar"

To explicitly create an Object without a prototype, use null as the prototype. This means the Object will not inherit from Object.prototype either and is useful for Objects used for existence checking dictionaries, e.g.

let objInheritingObject = {};
let objInheritingNull = Object.create(null);

'toString' in objInheritingObject; // true
'toString' in objInheritingNull ; // false

From ES6, the prototype of an existing Object can be changed using Object.setPrototypeOf, for example

let obj = Object.create({foo: 'foo'});
obj = Object.setPrototypeOf(obj, {bar: 'bar'});; // undefined; // "bar"

This can be done almost anywhere, including on a this object or in a constructor.

Note: This process is very slow in current browsers and should be used sparingly, try to create the Object with the desired prototype instead.


Before ES5, the only way to create an Object with a manually defined prototype was to construct it with new, for example

var proto = {fizz: 'buzz'};

function ConstructMyObj() {}
ConstructMyObj.prototype = proto;

var objWithProto = new ConstructMyObj();
objWithProto.fizz; // "buzz"

This behaviour is close enough to Object.create that it is possible to write a polyfill.