views:

121

answers:

4

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?

+5  A: 

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.

You may be wanting to implement sort of a StringBuilder perhaps?

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
CMS
No, i'm researching prototypes and checking out some things on inheritance and closures in JS. Interesting stuff and i had a vague feeling that a String was indeed immutable. It just seemed a little illogical that Array.pop could indeed modify itself (or the internal hash of values) but String couldn't modify itself. String eing one of the five primitives in JS explains alot though!
ChrisR
A: 

Strings are immutable; what you're asking is like saying, "Why can't I do:

Number.prototype.accumulate = function (x) {
    this = this + x;
};

...?"

Anthony Mills
+1  A: 

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

Matt Baker
A: 

I've been researching the same... First of all, of course you can't just do this += x, 'this' is an object, you can't use the + operator on objects.

There are 'behind the scene' methods that get called - for example

String.prototype.example = function(){ alert( this ); }

is actually calling

String.prototype.example = function(){ alert( this.valueOf() ); }

So what you need to find is a relevant value that does the the opposite - something like this.setValue(). Except that there isn't one. The same holds for Number too.

Even the built in methods are bound by that

var str = 'aaa';
str.replace( /a/, 'b' );
console.log( str ); // still 'aaa' - replace acts as static function 
str = str.replace( /a/, 'b' );
console.log( str ); // 'bbb' - assign result of method back to the object

On some other objects you can; for example on a Date:

Date.prototype.example = function(){
 this.setMonth( this.getMonth()+6 );
};
var a=new Date();
alert(a.getMonth());
a.example();
alert(a.getMonth());

It's annoying, but there you go

fritzfromlondon