Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

atad6

macrumors regular
Original poster
Jul 7, 2006
155
1
i've just learned how to use prototype and javascript and was playing around with adding methods to the string object.

is it possible to create a method that would actually change the string object's value, instead of using it to return another value. so for example if you added a method that turned the string backwards it would actually make the value of that string object backwards.
 
Can you provide some code laying out what you're trying to do? I'm not quite sure I understand what you're asking for.
 
When you create a class in javascript you can add methods which change the values of it's properties. In the example below I created a new object where the value of var1 is "oldstring". When I run the method changeval it actually changes the value of var1.

Below that I'm trying to do the same thing with a string. Since a string is an object in javascript it's possible to use prototype to add methods to it. However, I can't find a way to actually change the value of the string, as the code for the changestring() method does not work.

Code:
// Works
function newclass()
	{
	this.var1 = "oldstring";
	}

	newclass.prototype.changeval = function () {this.var1 = "newstring"};

	test = new newclass();

	document.write(test.var1);
	test.changeval();
	document.write(test.var1);

// Doesn't Work
	function changestring()
	{
	this = "newstring";
	}
	
	string1 = "oldstring";
	String.prototype.change = changestring;
	string1.change();
 
Almost, I realized I can add methods to the string object that return different values based on the value of the string, but I can't actually change the value of the string itself, which it's possible to do with properties in custom objects.

I've searched everywhere and can't seem to find an answer on this, I'm assuming it can't be done. I'm just confused as to why It isn't possible.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.