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

1

2 Answers 2

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';
};
Sign up to request clarification or add additional context in comments.

2 Comments

What I actually wanted was to change its value, I know returning this+"a" works fine. Anyway, thanks for the help
Treat strings in JavaScript as immutable. Work with the object returned from the function instead.
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 + '');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.