开发者问题收集

对象被识别为空或未定义

2022-09-09
175

我尝试将 housePrototype 指定为 House 对象的原型,但出现此错误

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

我做错了什么?

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);
3个回答

所有功劳都归功于 @JaromandaX。他在问题的评论中解释了这个问题。

尽管函数是 JavaScript 中的对象,但它们 并不 相同。要访问函数的原型,可以使用 function() {}.prototype 。但在问题中,它试图访问常规对象的原型,而不是未定义的函数对象,因此出现错误。

Object.assign(House.__proto__, housePrototype);

通过这种方式,可以将所需的对象分配给原型(不建议将任何变量分配给 proto ,而且这根本不是一个常见的做法)

解决方案代码将是

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');

我在以下 StackOverflow 线程中找到了完整的描述 __proto__ 与 JavaScript 中的原型

Inod Umayanga
2022-09-09

嘿兄弟,问题出在 House.prototpe,因为对象 house 没有名为原型的对象,只有两个名称和 readLocation,因此将代码更改为: 从此:

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

更改为此:

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, housePrototype)
  
  House.readLocation('Malabe');
  console.log(House);
Dev Contractor
2022-09-09

有用的文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#try_it

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(target, src);
Object.assign(House, housePrototype);

House.readLocation('Malabe');
console.log(House);
Daniel Madrid
2022-09-09