javascript - 如何在类中调用构造函数内的方法
问题描述
您好我正在尝试解决一个练习,我们必须创建一个类 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;
}
} ```
解决方案
推荐阅读
- excel - 如何将数据从一个电子表格粘贴到另一个电子表格的最后一列?
- python-3.x - 在 Python 中使用 Selenium 在 Google 专利中搜索后单击第一个链接/专利
- arrays - 为什么打字稿对我的 Array.filter 参数显示错误
- java - ModelMapper 中的自定义转换器没有被触发
- redux - 如何通过 ID ngrx 获取实体
- php - 如何使用 SMTP 驱动程序在 laravel 中发送批量电子邮件而不创建多个 smtp 客户端/会话
- python-3.x - 等待分离的容器运行
- spring-cloud-config - Spring Cloud Config Basic Security 抛出 401 错误
- java - 依赖于一个模块,该模块具有传递依赖的配置文件
- selenium - 如何不为依赖于该背景场景的 Cucumber 功能不断重复背景场景