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?
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?
Share Improve this question asked Oct 23, 2009 at 18:46 ChrisRChrisR 14.4k17 gold badges72 silver badges110 bronze badges3 Answers
Reset to default 19The 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.
Strings are immutable; what you're asking is like saying, "Why can't I do:
Number.prototype.accumulate = function (x) {
this = this + x;
};
...?"