【www.bbyears.com--js教程】
1 (function(window) {
var core_ArrPro = Array.prototype;
3 var core_slice = core_ArrPro.slice;
4 var core_push = core_ArrPro.push;
5 var core_unshift = core_ArrPro.unshift;
6
7 function StringBuffer() {
8 this.buffer = [];
9 }
10 StringBuffer.prototype = {
11 push: function() {
12 core_push.apply(this.buffer, core_slice.call(arguments));
13 return this;
14 },
15 unshift: function() {
16 core_unshift.apply(this.buffer, core_slice.call(arguments));
17 return this;
18 },
19 toString: function() {
20 return this.buffer.join("");
21 }
22 };
23 return window.StringBuffer = StringBuffer;
24 })(window);
25 document.getElementById("result").innerHTML = new StringBuffer().push("asdasd").unshift("654", 123).push(123, 564, "sdf");
由于apply效率低于call,而大多push操作只有1个参数,随更新为如下:
(function(window) {
var core_ArrPro = Array.prototype;
var core_slice = core_ArrPro.slice;
function StringBuffer() {
this.buffer = [];
}
StringBuffer.prototype = {
push: function() {
if(arguments.length == 1){
this.buffer.push(arguments[0])
}else if(arguments.length > 1){
this.buffer = this.buffer.concat(core_slice.call(arguments));
}
return this;
},
unshift: function() {
if(arguments.length == 1){
this.buffer.unshift(arguments[0])
}else if(arguments.length > 1){
this.buffer = core_slice.call(arguments).concat(this.buffer)
}
return this;
},
toString: function() {
return this.buffer.join("");
}
};
return window.StringBuffer = StringBuffer;
})(window);
document.getElementById("result").innerHTML = new StringBuffer().push("asdasd").unshift("654", 123).push(123, 564, "sdf");