Setting an object's prototype

suggest change

Object.create() creates an object with the specified object (or null) as its prototype.

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

const objWithProto = Object.create(anyObj);
objWithProto.foo = 'bar';

objWithProto.hello(); // "this.foo 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.

const objInheritingObject = {};
const 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'});

obj.foo; // undefined
obj.bar; // "bar"

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

Note: Changing the prototype of an existing object deoptimizes it in current engines. Create the object with the desired prototype instead.

Before ES5, the usual way to create an object with a chosen prototype was to construct it with new, for example

const proto = {fizz: 'buzz'};

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

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

This behaviour is close enough to Object.create that it is possible to write a polyfill. Assigning a non-object prototype does not produce an object whose prototype is null; new still uses Object.prototype in that case.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents