dan.lee
dan.lee

Reputation: 695

Javascript Program Syntax Error

I have a syntax error that I don't know how to fix. This is the code:

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);

On line 22, there is an error saying: Uncaught TypeError: Property 'price' of object # is not a function This is line 22:

var work_computer_price = work_computer.price();

Please help. Thanks!

Upvotes: 0

Views: 95

Answers (3)

Eliran Malka
Eliran Malka

Reputation: 16263

you better declare getPrice() as a member of the computer's prototype, like this:

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

Upvotes: 1

fsodano
fsodano

Reputation: 548

how are you?

The problem is that price is not a function, its an attribute.

So basically:

var work_computer_price = work_computer.price;

will work.

Cheers!

Upvotes: 0

Pointy
Pointy

Reputation: 413737

Take away the parentheses when you assign this.price:

this.price=get_price;

You want to set the "price" property to reference the function itself, not the return value of calling it.

Upvotes: 2

Related Questions