How to print a rectangle construct variabe in JavaScript?

C

cjeffwang

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
 
J

Joakim Braun

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

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 +
")");
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top