Wednesday, March 28, 2012

difference in creating toString()

I have created a .toString() on a custom object in two ways. Is there a
significant difference between two? they both seem to work. Is there a
reason to do one instead of the other?

This is done within the class definition:

this.toString = function(){
return _Name + " at " + _Address;
}

This is outside of the class def.
ExampleNamespace.cComplexCustomerType.prototype.toString = function(){
return this.getName() + " at " + this.getAddress();
}

--
Wallace B. McClure
"The Harder I Work, the Luckier I Get."
Listen to "The ASP.NET Podcast" at http://www.aspnetpodcast.com/
Database Award: http://url123.com/vc3er
Microsoft MVP - Visual Developer ASP/ASP.NET
AspInsider
"AJAX for ASP.NET" Coming Soon!
ADO.NET Book: http://url123.com/vc2bu
865-693-3004
118 Durwood Rd.
Knoxville, TN 37922
http://www.scalabledevelopment.com/
Blog: http://weblogs.asp.net/wallym/Hi,

everything added through theprototype object is shared between instances. Thus, if you declare the toString() function by expanding prototype, you are sharing the same code, while if you declare the function using thethis pointer, you are duplicating code.

There's nothing wrong in declaring functions using this or prototype, but the thing that must be avoided is pointing to *objects* through prototype, for example arrays.

Consider the following declaration:

function myObject() {
}
myObject.prototype.myArray = new Array('Item1', 'Item2');

Now, create two instances:

var obj1 = new myObject();
var obj2 = new myObject();

Add something to obj1's array:

obj1.myArray.push('Item3_by_obj1');

and finally display the two arrays:

alert(obj1.myArray);
alert(obj2.myArray);

As you can see, both the instances shares the same reference to myArray.

No comments:

Post a Comment