创建Product类实例时遇Uncaught TypeError错误,求排查
问题分析:Uncaught TypeError: Cannot read properties of undefined (reading 'image')
问题描述
尝试创建Product对象时传入参数对象,却持续报错:
Uncaught TypeError: Cannot read properties of undefined (reading 'image')
相关代码如下:
Product类代码
class Product { constructor(data) { this.image = this.data.image; this.volume = this.data.volume; this.name = this.data.name; this.url = this.data.url; this.price = this.data.price; this.uom = this.data.uom; } }
创建实例的代码
for (let i = 0; i < rootNodes.length; i++) { image = rootNodes[i].querySelector(".product-img").getAttribute("src"); volume = rootNodes[i].querySelector(".co-product__volume").textContent; name = rootNodes[i].querySelector(".co-product__anchor").textContent; url = rootNodes[i].querySelector(".co-product__anchor").href; price = rootNodes[i].querySelector(".co-product__price").childNodes[1]; uom = rootNodes[i].querySelector(".co-product__price-per-uom").textContent; var product = new Product({ image: image, volume: volume, name: name, url: url, price: price, uom: uom }); products.push(product); }
错误原因
构造函数里的错误非常直接:你在访问this.data,但你从未给实例的this添加过data属性。构造函数的参数是data,直接用这个参数即可,而不是this.data。this.data是undefined,所以读取它的image属性会抛出类型错误。
修正方案
把构造函数里的this.data替换成参数data:
class Product { constructor(data) { this.image = data.image; this.volume = data.volume; this.name = data.name; this.url = data.url; this.price = data.price; this.uom = data.uom; } }
可选优化:使用对象解构简化代码
如果参数data的属性和实例属性完全对应,可以用对象解构来简化构造函数,让代码更简洁:
class Product { constructor({ image, volume, name, url, price, uom }) { this.image = image; this.volume = volume; this.name = name; this.url = url; this.price = price; this.uom = uom; } } // 或者更简洁的批量赋值方式 class Product { constructor({ image, volume, name, url, price, uom }) { Object.assign(this, { image, volume, name, url, price, uom }); } }
额外注意点
创建实例的代码里,变量image、volume等没有用let或const声明,会变成全局变量,建议添加声明:
for (let i = 0; i < rootNodes.length; i++) { const image = rootNodes[i].querySelector(".product-img").getAttribute("src"); const volume = rootNodes[i].querySelector(".co-product__volume").textContent; const name = rootNodes[i].querySelector(".co-product__anchor").textContent; const url = rootNodes[i].querySelector(".co-product__anchor").href; const price = rootNodes[i].querySelector(".co-product__price").childNodes[1]; const uom = rootNodes[i].querySelector(".co-product__price-per-uom").textContent; const product = new Product({ image, volume, name, url, price, uom }); products.push(product); }
内容的提问来源于stack exchange,提问作者xertz
相关产品推荐
相关产品推荐

