Connecting Tech Pros Worldwide Help | Site Map

How to print a rectangle construct variabe in JavaScript?

  #1  
Old November 5th, 2005, 06:15 AM
cjeffwang@gmail.com
Guest
 
Posts: n/a
I am doing examples in "javascript: the Definitive Guide." For Example

8-1, a rectangle constructor function, how do I print/write the
rectagle (x,y)?


Here is the JavaScript program:


function Rectangle(w, h)
{
this.width = w;
this.height = h;



}


var rect1 = new Rectangle(2, 4);
var rect2 = new Rectangle(8.5, 11);

I tried to print "Rectangle (2,4)", by coding:


document.write("<h2>Rectangle</h2>");
document.write(rect1);


Previewing on FrontPage showed: Rectangle [object Object]


TIA,
Jeffrey

  #2  
Old November 5th, 2005, 08:25 AM
Joakim Braun
Guest
 
Posts: n/a

re: How to print a rectangle construct variabe in JavaScript?


<cjeffwang@gmail.com> skrev i meddelandet
news:1131170736.021547.23160@g47g2000cwa.googlegro ups.com...[color=blue]
> I am doing examples in "javascript: the Definitive Guide." For Example
>
> 8-1, a rectangle constructor function, how do I print/write the
> rectagle (x,y)?
>
>
> Here is the JavaScript program:
>
>
> function Rectangle(w, h)
> {
> this.width = w;
> this.height = h;
>
>
>
> }
>
>
> var rect1 = new Rectangle(2, 4);
> var rect2 = new Rectangle(8.5, 11);
>
> I tried to print "Rectangle (2,4)", by coding:
>
>
> document.write("<h2>Rectangle</h2>");
> document.write(rect1);[/color]

If you want do print "Rectangle(2,4)", then that's what you'll have to give
to document.write.
Objects aren't turned to strings by magic.

You can access the rectangle properties, and could write a function such as:

function writeRectangle(inRect){
document.write("Rectangle(" + inRect.width + ", " + inRect.height +
")");
}

--
Joakim Braun


  #3  
Old November 5th, 2005, 11:45 AM
Duncan Booth
Guest
 
Posts: n/a

re: How to print a rectangle construct variabe in JavaScript?


wrote:
[color=blue]
> document.write("<h2>Rectangle</h2>");
> document.write(rect1);
>
>
> Previewing on FrontPage showed: Rectangle [object Object][/color]

If you want a sensible representation of an object you have to tell the
system how to convert it to a string.

Try adding this after your definition of the Rectangle function:

Rectangle.prototype.toString = function() {
return "Rectangle("+this.width+","+this.height+")";
}
  #4  
Old November 6th, 2005, 06:05 AM
cjeffwang@gmail.com
Guest
 
Posts: n/a

re: How to print a rectangle construct variabe in JavaScript?


Thanks.

Closed Thread