qwertyuiop
07-30-2010, 01:49 AM
Is this possible?
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g, "");
}
var myStr = " Hi what's up? ";
myStr.trim();
alert("{" + myStr + "}"); //will result in the original string, not the trimmed version
It's possible with numbers:
var myNum = 10;
myNum++;
alert(myNum); //11
Old Pedant
07-30-2010, 02:08 AM
Of course.
var myStr = " Hi what's up? ";
myStr = myStr.trim();
Yeah, I know. It's not the same thing. But it's the best you'll do.
See, a string variable is just a *REFERENCE* to a string object. And string *objects* are immutable (means they can't be altered).
So any operation you do on a string *must* return a NEW string, since it's not allowed to touch the original string object.
But nobody said you can't change *which* string object a given variable references.
Old Pedant
07-30-2010, 02:10 AM
p.s.: You may have asked the question wrong.
If you had asked
Can I modify string *OBJECT* without creating a new *OBJECT*?
the answer is simply "no."
qwertyuiop
07-30-2010, 07:33 AM
^wtf? Lots of spam recently...
Thanks old pendant! I should kick myself... something that simple not coming to my head... :rolleyes:
So then, out of curiosity, numbers are simply mutable objects?
Old Pedant
07-30-2010, 08:29 PM
So then, out of curiosity, numbers are simply mutable objects?
I think now we are into both implementation and semantics. Not sure.
I know that in JScript (MS's version of JavaScript), numeric and boolean variables are indeed "mutable", but they aren't truly objects. The variable really is no longer a reference to an object; it carries the numeric/boolean value right inside of itself. (MS uses a COM "Variant" as the root implementation of a variable.)
But I would *expect* that if you used Number--the object-ized form of a number--then a Number object is immutable. Ditto a Boolean object.
A cursory glance at the MS JScript docs would seem to confirm this, but I'm not 100% sure.
How simple variables and values are implemented in other versions of JS I am not sure. (I only know about JScript because I once helped port it to Linux and Unix and IBM mainframes. That was back in JScript version 3.x days.)