2012-03-24 259 views
0

我有一個語法錯誤,我不知道如何解決。這是代碼:Javascript程序語法錯誤

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行,有一個錯誤說:遺漏的類型錯誤:對象#的特性「價格」是不是函數 這是第22行:

var work_computer_price = work_computer.price(); 

請幫幫我。謝謝!

+0

當然不是一個SyntaxError,但一個TypeError。 **提示**:使用'()'調用函數,並且在移除'()'時通過引用傳遞函數。 ** /結束提示** – 2012-03-24 21:52:24

回答

2

當你將this.price拿走括號:

this.price=get_price; 

你要設置的「價格」屬性引用函數本身,而不是調用它的返回值。

0

你好嗎?

的問題是,價格不是一個函數,它的屬性。

所以基本上:

var work_computer_price = work_computer.price; 

會工作。

乾杯!

1

你更好的聲明getPrice()computerprototype,像這樣的成員:

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; 
    } 
} 
+0

這將工作,如果它不是語法錯誤:-)(該函數需要聲明'get_price:function(){...}') – Pointy 2012-03-24 21:55:49

+0

謝謝,我在匆匆而過,只是注意到並糾正了錯誤。 – 2012-03-24 21:57:18

+1

如果覆蓋'.prototype',請確保恢復'.constructor'。 – pimvdb 2012-03-24 22:03:32