首页 > 解决方案 > 如何在类中调用构造函数内的方法

问题描述

您好我正在尝试解决一个练习,我们必须创建一个类 Appliance,然后创建两个子类(电视和洗衣机),然后我需要检查设备或它们的子类的颜色和消耗,如果没有通过它将通过一个方法被赋予一个默认值。到目前为止,这就是我所拥有的,但它一直告诉我 this.checkcolor 不是函数;我也尝试过类似的语法this.color = checkColor(color),并且还使用常量给出默认值,但似乎没有任何效果。最简单的方法是什么?谢谢

function Appliance(color, consumption, weight){     

    this.color = this.checkColor(color);
    this.consumption =  this.checkConsumption(consumption);
    this.weight = weight || 5;  
    this.price = this.getPrice(this.consumption, this.weight);

    Appliance.prototype.checkConsumption = function(consumption){
        let res = "";
        const consumptions = ["A", "B", "C", "D", "E", "F"];
        for(let i = 0; i < consumptions; i++){
            if(consumptions[i] == consumption){
                res = consumption;
            }
            else{
                res = "F";
            }
        }
        return res
    }       

    Appliance.prototype.checkColor = function(color){
        let res = "";       
        let checker = false;
        const colors = ["white", "red", "blue", "grey"];
        for(let i = 0; i < colors.length && !checker; i++){
            if(colors[i] == color){
                checker = true;
            }           
        }

        if(checker){
            res = color;
        }
        else{
            res = "white";
        }   
        return res;
    }

    Appliance.prototype.getPrice = function(consumption, weight){
        let defaultPrice = 100;
        let extra = 0;
        switch(consumption){
            case "A":
            extra += 100;
            break;
            case "B":
            extra += 80;
            break;
            case "C":
            extra += 60;
            break;
            case "D":
            extra += 50;
            break;
            case "E":
            extra += 30;
            break;
            case "F":
            extra += 10;
            break;
        }

        if(weight >= 0 && weight < 19){
            extra += 10;
        }else if(weight >= 20 && weight < 49){
            extra += 50;
        }else if(weight >= 50 && weight <= 79){
            extra += 80;
        }else if(weight >= 80){
            extra += 100;
        }

        return defaultPrice + extra;
    }   

    Appliance.prototype.getColor = function(){
        return this.color;      
    }

    Appliance.prototype.getConsumption = function(){
        return this.consumption;
    }

    Appliance.prototype.getWeight = function(){
        return this.weight;
    }
} ```

标签: javascriptclass

解决方案


推荐阅读