使用Object.assign为House对象设置原型触发TypeError错误求解答
问题原因与解决方案
错误原因
你定义的House是普通对象,只有构造函数(或class)才有prototype属性,普通对象的prototype是undefined。而Object.assign的第一个参数必须是对象,传入undefined就会抛出Cannot convert undefined or null to object的错误。
正确做法分两种情况:
1. 给普通对象设置原型
如果想让housePrototype成为House的原型,用Object.setPrototypeOf()方法:
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}`) } } // 设置House的原型为housePrototype Object.setPrototypeOf(House, housePrototype) // 优先调用自身的readLocation House.readLocation('Malabe'); // 输出:house is located at Malabe // 删除自身的readLocation后,会调用原型上的方法 delete House.readLocation; House.readLocation('Malabe'); // 输出:house prototype is located at Malabe console.log(House);
2. 直接合并属性到House对象
如果只是想把housePrototype的属性合并到House自身(覆盖同名属性),直接把House作为Object.assign的第一个参数:
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}`) } } // 合并属性到House自身,覆盖原readLocation Object.assign(House, housePrototype) House.readLocation('Malabe'); // 输出:house prototype is located at Malabe console.log(House);
3. 若本意是创建构造函数/类
如果你的目标是定义一个可实例化的类,应该把House定义为构造函数或class,此时才有prototype属性:
// 构造函数写法 function House() { this.name = 'houseObject'; } House.prototype.readLocation = (location)=>{ console.log(`house is located at ${location}`) } const housePrototype = { readLocation: (location) => { console.log(`house prototype is located at ${location}`) } } // 合并到构造函数的prototype上 Object.assign(House.prototype, housePrototype) const myHouse = new House(); myHouse.readLocation('Malabe'); // 输出:house prototype is located at Malabe
内容的提问来源于stack exchange,提问作者Inod Umayanga
相关产品推荐
相关产品推荐

