Reputation: 14379
What is going on behind the scenes here for each script. Assuming that I will be getsize()
alot, is there any difference between the code:
Code 1:
function Size (width, height)
{
this.width = width;
this.height = height;
}
function getSize()
{
return new Size (0, 0);
}
Code 2
function getSize ()
{
return {width: 0; height: 0};
}
I think they are equivalent both in all senses but just wanted to check.
Upvotes: 2
Views: 102
Reputation: 15802
They're (essentially) equivalent now, but only until Size
's prototype changes. If that changes at any point in the future, your {width: 0, height: 0}
will be incorrect, so it's probably better to use return new Size(0, 0);
The only real difference is that the Size
object is an instance of a different object to a generic JS object:
var a = new Size(0,0);
var b = {width:0, height:0};
alert(a == b) // would be false even if JS didn't always say two objects are different (see comments)
Upvotes: 0
Reputation: 47172
In the first code example you're returning a named object called Size, in the second code you're returning an anonymous javascript object. Thus you lose the Size objects constructor and prototype hindering you to extend all similar objects further.
Upvotes: 2