2012-03-24 6 views
0

修正方法がわからない構文エラーがあります。Javascript Program構文エラー

ライン22で
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); 

、というエラーがあります:キャッチされない例外TypeError:オブジェクト#のプロパティ「価格は」これは22行である機能 ではありません。

var work_computer_price = work_computer.price(); 

してくださいこれはコードです助けて。ありがとう!あなたがthis.priceを割り当てるときに

+0

確かではないでSyntaxErrorが、例外TypeError。 **ヒント**:関数は '()'を使って呼び出され、 '()'が削除されたときに参照渡しされます。 ** /ヒントの終わり** –

答えて

2

は括弧を奪う:

this.price=get_price; 

をあなたは関数自体ではなく、それを呼び出しの戻り値を参照するために「価格」プロパティを設定します。

0

元気?

問題は、価格は関数、その属性ではないということです。そこで、基本的

var work_computer_price = work_computer.price; 

が動作します。

乾杯!

1

方が良い、このように、computerprototypeのメンバーとしてgetPrice()を宣言:

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

+0

ありがとう、私はラッシュとそれだけで気づいて修正したスリット。 –

+1

'.prototype'を上書きする場合は、必ず' .constructor'を復元してください。 – pimvdb

関連する問題