Skyzyx
12-21-2002, 06:36 AM
I've been reading Danny Goodman's JavaScript Bible, and in chapter 41, it talks about creating custom objects with functions, etc.
Here's a to-the-point example of what he does:
function showPlanet()
{
document.write(this.name);
}
function planet(name, diameter, distance, year, day)
{
this.name = name;
this.diameter = diameter;
this.distance = distance;
this.year = year;
this.day = day;
this.showPlanet = showPlanet; // make showPlanet() function a method of
}
var Mercury = new planet("Mercury","3100 miles", "36 million miles", "88 days", "59 days");
var Venus = new planet("Venus", "7700 miles", "67 million miles", "225 days", "244 days");
He also briefly discusses "anonymous" functions as well as nested functions. He didn't go over it enough for me to get how these all work.
Now, is there a way to make this all one single function? And how would you pass variables to the function as you would with "function bob(var)"? I'm thinking it may work out something like this...
function planet(name, diameter, distance, year, day)
{
this.name = name;
this.diameter = diameter;
this.distance = distance;
this.year = year;
this.day = day;
this.showPlanet = new function ()
{
document.write(this.name);
}
}
I've tried a couple of combinations of things like this, but I keep getting errors like "Mercury.showPlanet() is not a function". How would this work (in the general sense)?
PS: I saw this being done in this post: http://www.codingforums.com/showthread.php?s=&threadid=11585, but I'm still a little fuzzy...
Here's a to-the-point example of what he does:
function showPlanet()
{
document.write(this.name);
}
function planet(name, diameter, distance, year, day)
{
this.name = name;
this.diameter = diameter;
this.distance = distance;
this.year = year;
this.day = day;
this.showPlanet = showPlanet; // make showPlanet() function a method of
}
var Mercury = new planet("Mercury","3100 miles", "36 million miles", "88 days", "59 days");
var Venus = new planet("Venus", "7700 miles", "67 million miles", "225 days", "244 days");
He also briefly discusses "anonymous" functions as well as nested functions. He didn't go over it enough for me to get how these all work.
Now, is there a way to make this all one single function? And how would you pass variables to the function as you would with "function bob(var)"? I'm thinking it may work out something like this...
function planet(name, diameter, distance, year, day)
{
this.name = name;
this.diameter = diameter;
this.distance = distance;
this.year = year;
this.day = day;
this.showPlanet = new function ()
{
document.write(this.name);
}
}
I've tried a couple of combinations of things like this, but I keep getting errors like "Mercury.showPlanet() is not a function". How would this work (in the general sense)?
PS: I saw this being done in this post: http://www.codingforums.com/showthread.php?s=&threadid=11585, but I'm still a little fuzzy...