JS: Object.setPrototypeOf

By Xah Lee. Date: . Last updated: .

(new in JS: ECMAScript 2015)

Object.setPrototypeOf(obj, parent)

Set the parent of obj to parent. Return the changed obj.

💡 TIP: better is JS: Reflect.setPrototypeOf because it error out if argument is not an object.

const aa = {};

// create a child object bb whose parent is aa
const bb = Object.create(aa);

// bb's parent is aa
console.log(Reflect.getPrototypeOf(bb) === aa);

// now change parent
const cc = Object.setPrototypeOf(bb, Array);

// return value is the new bb
console.log(cc === bb);
console.log(Reflect.getPrototypeOf(bb) === Array);
// no error, if arg is not object
const zz = Object.setPrototypeOf(2, Array);

JavaScript. Get Set Prototype