Luk*_*ull -1 javascript methods console object
基本上我用一个方法创建了一个对象,该方法在对象中添加了几个属性.但是当我尝试将该方法调用到控制台日志时,它会向我发出代码(这是一个if语句),而不是我希望它返回的值,所以我很困惑!为什么会这样?代码如下:
var Granite = function(ty, gr, th, wi, le, ed, ad){
this.type = ty;
this.group = gr;
this.thickness = th;
this.width = wi;
this.length = le;
this.edgeProfile = ed;
this.addOns = ad;
this.groupPrice = function(){
if (thickness === 20){
switch(group)
{
case 1:
return 160;
break;
case 2:
return 194;
break;
case 3:
return 244;
break;
case 4:
return 288;
break;
case 5:
return 336;
break;
case 6:
return 380;
break;
default:
return 380;
}
}else{
switch(group)
{
case 1:
return 200;
break;
case 2:
return 242;
break;
case 3:
return 305;
break;
case 4:
return 360;
break;
case 5:
return 420;
break;
case 6:
return 475;
break;
default:
return 475;
}
}
}
this.price = function(){
if(length <= 2000 && length > 1000){
return ((edgeProfile + groupPrice)*2) - addOns;
}else if(length <= 3000 && length > 2000){
return ((edgeProfile + groupPrice)*3) - addOns;
}else if(length <= 4000 && length > 3000){
return ((edgeProfile + groupPrice)*4) - addOns;
}else if(length <= 5000 && length > 4000){
return ((edgeProfile + groupPrice)*5) - addOns;
}
}
}
var granite1 = new Granite("Rosa Porrino", 1, 30, 400, 3200, 30.05, 86.18);
console.log(granite1.groupPrice);
Run Code Online (Sandbox Code Playgroud)
它将groupPrice方法中的完整if语句返回给我
您没有调用该方法,而是向控制台提供函数引用,log().在JavaScript中,您需要使用'()'来调用函数.
这肯定会奏效 console.log(granite1.groupPrice());
在这边.价格
用 this.groupPrice().代替groupPrice
修改了这个,价格方法
this.price = function(){
if(length <= 2000 && length > 1000){
return ((this.edgeProfile + this.groupPrice())*2) - addOns;
}else if(length <= 3000 && length > 2000){
return ((this.edgeProfile + this.groupPrice())*3) - addOns;
}else if(length <= 4000 && length > 3000){
return ((this.edgeProfile + this.groupPrice())*4) - addOns;
}else if(length <= 5000 && length > 4000){
return ((this.edgeProfile + this.groupPrice())*5) - addOns;
}
}
Run Code Online (Sandbox Code Playgroud)