문자열을 array join 방식으로 결합하는 StringBuffer 봉인

6874 단어 StringBuffer
 1 (function(window) {

 2     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');

좋은 웹페이지 즐겨찾기