我有一个语法错误,我不知道如何修复。这是代码:
function computer(speed, hdspace, ram)
{
this.speed=speed;
this.hdspace=hdspace;
this.ram=ram;
this.price=get_price();
}
function get_price()
{
var the_price=500;
the_price += (this.speed == "2GHz") ? 200 : 100;
the_price += (this.hdspace == "80GB") ? 50 : 25;
the_price += (this.ram == "1GB") ? 150 : 75;
return the_price;
}
var work_computer = new computer("2GHz", "80GB", "1GB");
var home_computer = new computer("1.5GHz", "40GB", "512MB");
var laptop_computer = new computer("1GHz", "20GB", "256");
var price = get_price();
var work_computer_price = work_computer.price();
var home_computer_price = home_computer.price();
var laptop_computer_price = laptop_computer.price();
document.write("<h1>Prices of the computers you requested:</h1>");
document.write("<h3><br/>Work Computer: </h3>"+work_computer);
document.write("Price: $"+work_computer_price);
document.write("<br/>");
document.write("Home Computer: "+home_computer);
document.write("Price: $"+home_computer_price);
document.write("<br/>");
document.write("Laptop Computer: "+laptop_computer);
document.write("Price: $"+laptop_computer_price);
在第22行,有一个错误说:未捕获TypeError:对象#的属性'价格'不是函数 这是第22行:
var work_computer_price = work_computer.price();
请帮忙。谢谢!
答案 0 :(得分:2)
分配this.price
时取消括号:
this.price=get_price;
你想设置“price”属性来引用函数本身,而不是调用它的返回值。
答案 1 :(得分:1)
您最好将getPrice()
声明为computer
prototype
的成员,如下所示:
var computer = function(speed, hdspace, ram)
{
this.speed=speed;
this.hdspace=hdspace;
this.ram=ram;
this.price=get_price();
}
computer.prototype = {
get_price: function()
{
var the_price=500;
the_price += (this.speed == "2GHz") ? 200 : 100;
the_price += (this.hdspace == "80GB") ? 50 : 25;
the_price += (this.ram == "1GB") ? 150 : 75;
return the_price;
}
}
答案 2 :(得分:0)
问题在于价格不是一种功能,而是一种属性。
基本上是这样的:
var work_computer_price = work_computer.price;
会奏效。
干杯!