javascript adding method to string object

Discussion in 'Web Design and Development' started by atad6, Dec 13, 2007.

  1. atad6 macrumors regular

    Joined:
    Jul 7, 2006
    #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.
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    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.
     
  3. atad6 thread starter macrumors regular

    Joined:
    Jul 7, 2006
    #3
    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();
     
  4. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #4
  5. atad6 thread starter macrumors regular

    Joined:
    Jul 7, 2006
    #5
    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.
     
  6. bootedbear macrumors 6502

    bootedbear

    Joined:
    Sep 13, 2004
    Location:
    Austin, TX
    #6
    The String implementation is purposefully designed to be immutable.
     
  7. atad6 thread starter macrumors regular

    Joined:
    Jul 7, 2006

Share This Page