To Top

Our Blog

Guru Technologies

Javascript Object Switcheroo

So I found out something interesting with javascript and objects. Let’s say you have a cube object in javascript that is defined by this function.

function Cube(x, y, z);

Now lets say we had set the z value to be zero. Why would we want a cube object when it is really just a plane?

function Cube(x, y, z)
{
	this.x = x;
	this.y = y;
	this.z = z;
	this.type = 'Cube';
	if(z == 0)
	{
		return new Plane(x, y);
	}
}

function Plane(x, y)
{
	this.x = x;
	this.y = y;
	this.type = 'Plane';
}

If we do this code here:

var shape = new Cube(4, 2, 0);

If we were to inspect shape what type of object will it be?

If we did something like document.write(shape.type) the answer will be Plane.


Warning: Declaration of guru_walker_comment::start_el(&$output, $comment, $depth, $args, $id = 0) should be compatible with Walker_Comment::start_el(&$output, $comment, $depth = 0, $args = Array, $id = 0) in /var/www/html/wp-content/themes/guru-new/guru-walker-comment.php on line 0

No comments