...

View Full Version : Quick Question on Assigning Method to Object



Ahlahn
12-29-2010, 08:02 PM
function get_price()
{
var the_price=1000;
if (this.speed=="500MGz")
the_price+=200;
else
the_price+=100;
if (this.hdspace=="15GB")
the_price+=50;
else
the_price+=25;
if (this.ram=="128MB")
the_price+=150;
else
the_price+=75;
return the_price;
}

function computer(speed,hdspace,ram)
{
this.speed=speed;
this.hdspace=hdspace;
this.ram=ram;
this.price=get_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","256MB");

var work_computer_price=work_computer.price();
var home_computer_price=home_computer.price();
var laptop_computer=laptop_computer.price();


___________________________________________________

In the above code, the line I'm having trouble with is marked red.

Why is it that when I call the method using ...

this.price = get_price;

It works fine.

But if I assign the object this.price with like this...

this.price = get_price();

I get an error?

Isn't get_price() a function? So shouldn't the parenthesis be included when the method is called? Why are we suppose to leave out the parenthesis?! I'm confused.

Thanks!

Old Pedant
12-29-2010, 09:18 PM
You are *NOT* "calling" the function when you do this.price = get_price;

You are, for all intents and purpose, making this.price an *ALIAS* for get_price.

That is, you have assigned a *REFERENCE* to the function to the member varialbe price. So that later you could do (as you are indeed doing) work_computer.price();

The reason that doing this.price = get_price() barfs on your feet is that then you *ARE* invoking the function. But then when you get into the function, the keyword this has NO REFERENCE object to refer to!!! That is, at that point this is either null or maybe refers to the whole document.

rnd me
12-29-2010, 11:34 PM
this.price = get_price.call(this);

Old Pedant
12-29-2010, 11:54 PM
I was going to do it uglier, but yeah...why not.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum