首页 > 解决方案 > 无法理解出了什么问题

问题描述

我编写此代码作为工厂模式的练习,但出现错误,我不知道为什么。

代码:

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

标签: javascript

解决方案


问题是:如果你传递一个无效的,工厂会怎么做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;
    }
}

推荐阅读