javascript - 无法理解出了什么问题
问题描述
我编写此代码作为工厂模式的练习,但出现错误,我不知道为什么。
代码:
class ShopFactory {
constructor (item, type, name) {
let shelf;
if(type === "toiletries"){
shelf = new Toiletries(item, name);
}else if (type === "cosmetics") {
shelf = new Cosmetics(item, name);
}else if (type === "foods") {
shelf = new Foods(item, name);
}else if (type === "beautifications"){
shelf = new Beautifications(item, name);
}
shelf.type = type;
shelf.func = function () {
console.log(`${this.item}--${this.type}--${this.name} Cost: ${this.cost}`);
}
return shelf;
}
}
class Toiletries{
constructor (item, name){
this.item = item;
this.name = name;
this.cost = "$15";
}
}
class Cosmetics{
constructor (item, name){
this.item = item;
this.name = name;
this.cost = "$30";
}
}
class Foods{
constructor (item, name){
this.item = item;
this.name = name;
this.cost = "$20";
}
}
class Beautifications{
constructor (item, name){
this.item = item;
this.name = name;
this.cost = "$25";
}
}
var shelves = [];
shelves.push(new ShopFactory("grocery","foods","rice"));
shelves.push(new ShopFactory("cleaning","toiletries","toilet-cleaner"));
shelves.push(new ShopFactory("machine-tools","beautifications","screw-driver"));
shelves.push(new ShopFactory("powder","Cosmetics","body-powder"));
shelves.push(new ShopFactory("cleaning","beautifications","wand"));
shelves.push(new ShopFactory("grocery","foods","fish"));
console.log(shelves);
Error:
Uncaught TypeError: Cannot set property 'type' of undefined
at ShopFactory.createShelf (app2.js:18)
at app2.js:60
createShelf @ app2.js:18
(anonymous) @ app2.js:60
解决方案
问题是:如果你传递一个无效的,工厂会怎么做type
,例如"Cosmetics"
?请记住,上限很重要。您应该抛出一个适当的信息错误,否则shelf
将不会被设置并且您正在尝试这样做(undefined).type = type;
:
class ShopFactory {
constructor(item, type, name) {
let shelf;
if (type === "toiletries") {
shelf = new Toiletries(item, name);
} else if (type === "cosmetics") {
shelf = new Cosmetics(item, name);
} else if (type === "foods") {
shelf = new Foods(item, name);
} else if (type === "beautifications") {
shelf = new Beautifications(item, name);
} else {
throw new Error(`Unknown type '${type}'`);
}
shelf.type = type;
shelf.func = function () {
console.log(`${this.item}--${this.type}--${this.name} Cost: ${this.cost}`);
}
return shelf;
}
}
推荐阅读
- php - Elasticsearch PHP 添加路由到子文档
- flutter - 找不到方法:'setState' 即使我在有状态的小部件中
- python - 根据条件创建 bin
- mysql - 如何根据正则表达式查询将是或否值插入标志列
- arrays - C 用 printf 打印非常奇怪的值
- python - 赋值前引用的全局变量?
- widget - 散景:滑块未更新 Hbar 图上的结果
- javascript - 如何将基于 URL 的 mp3 文件从客户端上传到节点服务器
- python - Google Drive API 权限不足:请求的身份验证范围不足
- html - Alpinejs 嵌套 x-data 范围问题?