String prototype modifying itself

后端 未结 4 2112
广开言路
广开言路 2021-02-20 16:09

As far as i know it\'s not possible to modify an object from itself this way:

String.prototype.append = function(val){
    this = this + val;
}

4条回答
  •  北海茫月
    2021-02-20 17:05

    The String primitives are immutable, they cannot be changed after they are created.

    Which means that the characters within them may not be changed and any operations on strings actually create new strings.

    Perhaps you want to implement sort of a string builder?

    function StringBuilder () {
      var values = [];
    
      return {
        append: function (value) {
          values.push(value);
        },
        toString: function () {
          return values.join('');
        }
      };
    }
    
    var sb1 = new StringBuilder();
    
    sb1.append('foo');
    sb1.append('bar');
    console.log(sb1.toString()); // foobar
    

提交回复
热议问题