10

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?

ChrisR
  • 14,370
  • 16
  • 70
  • 107

3 Answers3

19

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
I159
  • 29,741
  • 31
  • 97
  • 132
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • No, i'm researching prototypes and checking out some things on inheritance and closures in JS. Interesting stuff and i had a vague feeling that a String was indeed immutable. It just seemed a little illogical that Array.pop could indeed modify itself (or the internal hash of values) but String couldn't modify itself. String eing one of the five primitives in JS explains alot though! – ChrisR Oct 23 '09 at 19:30
  • It seems quite unintuitive to have an API where the variable sb1 is not an instance of a StringBuilder after `var sb1 = new StringBuilder()`. Why not assign { append: ... } to StringBuilder.prototype and change `var values = []` to `this.values = []`? Is this just to avoid prefixing values in append/toString with `this.` or is there something I'm not considering here? – ledneb Sep 27 '12 at 09:54
3

While strings are immutable, trying to assign anything to this in any class will throw an error.

Matt Baker
  • 3,694
  • 1
  • 20
  • 16
-3

Strings are immutable; what you're asking is like saying, "Why can't I do:

Number.prototype.accumulate = function (x) {
    this = this + x;
};

...?"

Anthony Mills
  • 8,676
  • 4
  • 32
  • 51