↑
Main Page
practical example
Which one to use?
As mentioned previously, the hybrid constructor/prototype paradigm is the one most widely used at
present. That being said, dynamic prototyping is catching on in popularity and is functionally equiva-
lent. Using either of these two methods is perfectly fine. Don’t ever get caught using the classic, con-
structor or prototype paradigms alone, however, because you may introduce problems into code.
A practical example
Part of the appeal of objects is the way they can be used to solve problems. One of the common problems
in ECMAScript is the performance of string concatenation. Similar to other languages, ECMAScript
strings are
immutable
, meaning that their value cannot be changed. Consider the following code:
var str = “hello “;
str += “world”;
This code actually executes the following steps behind the scenes:
1.
Create a string to store
“hello “
.
2.
Create a string to store
“world”
.
3.
Create a string to store the result of concatenation.
4.
Copy the current contents of
str
into the result.
5.
Copy the
“world”
into the result.
6.
Update
str
to point to the result.
Steps 2–6 occur every time a string concatenation is completed, making this a very expensive operation.
If this process is repeated hundreds or even thousands of times, performance suffers. The solution is to
use an
Array
object to store the strings and then use the
join()
method (with an empty string as an
argument) to create the final string. Imagine writing this code instead:
var arr = new Array;
arr[0] = “hello “;
arr[1] = “world”;
var str = arr.join(“”);
Using this method, it doesn’t matter how many strings are introduced into the array because the only
concatenation occurs when the
join()
method is called. At that point, the following steps are executed:
1.
Create a string to store the result.
2.
Copy each string into the appropriate spot in the result.
Although this solution is good, it could be better. The problem is that the code doesn’t accurately reflect
its intent. To make it more understandable, this functionality can be wrapped in a
StringBuffer
class:
function StringBuffer() {
this.__strings__ = new Array;
}
97
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 97
Free JavaScript Editor
Ajax Editor
©
→