0

I'm trying to change the string value inside its protoype function:

String.prototype.myfunction=function(){
    this += "a";
    return this;
};

But as it seems I just can't change the value. If I try to run that on the console I just get the error: Uncaught ReferenceError: Invalid left-hand side in assignment

Is it possible to change the strings value? Thanks in advance

Marcelo43
  • 57
  • 7
  • See also [how do i get “this = this” in prototype working](http://stackoverflow.com/q/28148196/1048572) or [Assign object to “this”](https://stackoverflow.com/questions/15598549/assign-object-to-this) – Bergi Nov 20 '16 at 22:32

2 Answers2

3

I think it has to do with the immutability of strings and the fact that this is a constant.

It works just fine if your example is trivially changed to:

String.prototype.myfunction=function(){
    return this + 'a';
};
Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
0

Strings are immutable. You may want to use an array of characters instead:

class MyString extends Array {
  constructor(str) {
    super(...String(str));
  }
  myfunction() {
    this.push("a");
    return this;
  }
  toString() {
    return this.join('');
  }
}
var s = new MyString("hello!");
s.myfunction();
console.log(s + '');
Oriol
  • 274,082
  • 63
  • 437
  • 513