Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String prototype modifying itself

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?

like image 641
ChrisR Avatar asked Oct 23 '09 18:10

ChrisR


People also ask

Why is it a bad idea to modify prototypes?

The problem is that prototype can be modified in several places. For example one library will add map method to Array's prototype and your own code will add the same but with another purpose. So one implementation will be broken.

What is string prototype?

The prototype is a property available with all JavaScript objects. The prototype property allows you to add new properties and methods to strings.

Which string prototype method takes a regular expression?

prototype.search() The search() method executes a search for a match between a regular expression and this String object.

How do I duplicate a string in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.


2 Answers

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
like image 142
Christian C. Salvadó Avatar answered Oct 16 '22 08:10

Christian C. Salvadó


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

like image 39
Matt Baker Avatar answered Oct 16 '22 06:10

Matt Baker