Currently, the most widely used is the hybrid constructor/prototype method. In addition, the dynamic prototype method is also popular, which is functionally equivalent to the constructor/prototype method. Either of the two methods can be used. However, do not use the classic constructor or prototype separately.
Do you still remember what the constructor is like?
Function tree (name, type ){
This. Name = Name;
This. type = type;
...
}
VaR otree = new tree ("Av", "unknown"); // instantiate an object
There are also prototype methods:
Function tree (){
Tree. Prototype. Name = "Av ";
Tree. Prototype. type = "unknown ";
...
}
VaR otree = new tree (); // instantiate an object
Consider the following code
var str = “Hello”;str+ = “world”;
In fact, the following code is executed:
- Create a string that stores "hello.
- Create a string that stores "world.
- Create a string that stores the connection result.
- Copy the current STR content to the result.
- Copy "world" to the result.
- Update STR to point it to the result.
The following method only takes two steps:
var arr = new Array;arr[0] = “helllo”;arr[1] = “world”;var str = arr.join(“”);
- Create a string for storing the result.
- Copy each string to a proper position in the result.
This method is good, but it is better. To make it easier to understand, you can use the stringbuffer class to package this function:
function StringBuffer (){ this._strings_ = new Array;}StringBuffer.prototype.append = function (str){ this._strings_.push(str);};StringBuffer.prototype.toString = function () { return this._strings_.join(“ ”);}
The first thing to note in this code is the strings attribute, which is intended to be a private attribute. It has only two methods, append () and tostring. Append () has only one parameter. It returns this parameter to the string array. The tostring () method calls the join () method of the array and returns the truly connected string. Use the following code to connect a group of strings with the stringbuffer object:
var buffer = new StringBuffer();buffer.append(“hello”);buffer.append(“world”);var result = buffer.toString();
Use the following code to test the performance of the stringbuffer object and the Traditional string connection method:
var d1 = new Date();var str = “”;for (var i=0;i<10000;i++){ str+ = “test”}var d2 = new Date ();document.write(“Concatenation with plus:”+(d2.getTime() – d1.getTime())+”milloseconds”);var oBuffer = new StringBuffer ();d1 = new Date ();for(var i=0;i<10000;i++){ oBuffer.append(“text”);}var sResult = buffer.toString ();d2 = new Date();document.write(“<br/>Concatenation with StringBuffer:”+(d2.getTime() – d1.getTime())+”milloseconds”);
Test results: Use stringbuffer to save 50%-60% of the time by using the plus sign.