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?
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.
The prototype is a property available with all JavaScript objects. The prototype property allows you to add new properties and methods to strings.
prototype.search() The search() method executes a search for a match between a regular expression and this String object.
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.
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
While strings are immutable, trying to assign anything to this
in any class will throw an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With