字符串原型修改自身

问题描述:

据我所知,不可能以这种方式从自身修改对象:

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;
}

那么是不是根本不可能让一个字符串函数修改自己?

So is it not possible at all to let a string function modify itself?

String 原语是不可变的,它们在创建后不能改变.

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