String prototype modifying itself

javascript, prototype, string

Solution

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

Problem

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?

Original source