1

When an object is created, its prototype is also set to an object.

After an object is created, can its prototype be changed to a different object?

halfer
  • 19,824
  • 17
  • 99
  • 186
Tim
  • 1
  • 141
  • 372
  • 590
  • Possible Duplicate: https://stackoverflow.com/questions/7015693/how-to-set-the-prototype-of-a-javascript-object-that-has-already-been-instantiat (though the answer here is better imo) – Kevin B May 09 '19 at 22:42

1 Answers1

1

Sure you can use Object.setPrototypeOf() (link has some useful warnings as well):

let parent = {
    test: "hello"
}

let child = {}
// object
console.log(Object.getPrototypeOf(child))

Object.setPrototypeOf(child, parent)
// parent now prototype
console.log(Object.getPrototypeOf(child))

// can access parent props
console.log(child.hasOwnProperty('test')) // not on child object
console.log(child.test)
Mark
  • 90,562
  • 7
  • 108
  • 148