Search code examples
javascripttypeerrorjavascript-objectsprototypeassign

Object being recognized as null or undefined


I'm trying to assign housePrototype as the prototype of House object, and followed up with this error

Object.assign(House.prototype, this.housePrototype); ^ TypeError: Cannot convert undefined or null to object

What am I doing wrong?

const House = {
    name: 'houseObject',
     readLocation: (location)=>{
      console.log(`house is located at ${location}`)
    }
  }

  const housePrototype = {
    readLocation: (location) => {
    console.log(`house prototype is located at ${location}`)
    }
  }

  Object.assign(House.prototype, housePrototype)
  
  House.readLocation('Malabe');
  console.log(House);


Solution

  • All credit goes to @JaromandaX. He explained the issue in the comments of the question.

    Even though functions are Objects in JavaScript they are NOT identical. To access the prototype of a function function() {}.prototype can be used. But in the question, it is trying to access the prototype of a regular object, not a function object, which is undefined, thus the error.

    Object.assign(House.__proto__, housePrototype); 
    

    With this it is possible to assign desired object to the prototype (It is not recommended to assign any variables to proto and it si not at all a common pra)

    The solution code would be

    const House = {
        name: 'houseObject',
         readLocation: (location)=>{
          console.log(`house is located at ${location}`)
        }
      }
    
      const housePrototype = {
        readLocation: (location) => {
        console.log(`house prototype is located at ${location}`)
        }
      }
    
      Object.assign(House.__proto__, housePrototype)
      
      House.readLocation('Malabe');

    I found a complete description in following StackOverflow thread __proto__ VS. prototype in JavaScript