PDA

View Full Version : creating object methods



pruijter
August 31st, 2002, 08:38 AM
Hello,

How do I create a method in an object,
Thanks
Pierre

example:
// code
function house(type, location) // constructor "house"
{
this.type = type;
this.location = location;
}

house1 = new house(villa, hawai); //creating an instance
// end code

For retrieving e.g. the variables type and location, how do I create the methods getType and getLocation.

I expected the following would work but it does not:
//code
function house(type, location) //constructor
{
this.type = type;
this.location = location;

function getType() // create method getType
{ return type; }
function getLocation() // create method getLocation
{ return location; }

}

house1 = new house(villa, hawai); //create an instance
houseType1 = house1.getType(); // retrieve variables
houseLocation1 = house1.getLocation();
trace( houseType+" "+houseLocation1); // print variables

// end code

Bezzer
September 1st, 2002, 04:35 AM
i see what you are trying to do but i dont know how to achieve it :) oh well maybe someone else might?

pom
September 1st, 2002, 09:57 AM
Several ways to do that. The easiest would be to add a method to the prototype of your class (which should only contain the methods of the Object class for now):
house.prototype.getType=function ()
{
return this.type;
}pom :asian:

pom
September 1st, 2002, 10:04 AM
You make quite a big mistake by the way, forgetting this in your function. You have to put it whenever you create a method.

pom :P