JS: Object.setPrototypeOf ❌

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

🟢 TIP: better is Reflect.setPrototypeOf.

Object.setPrototypeOf(obj, parent)

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

🛑 WARNING: no error, if arg is not object.

const aa = {};

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

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

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

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

JavaScript. Get Set Prototype