Search code examples
javascriptprototype

Can the prototype of an object be changed to another object?


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?


Solution

  • 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)