views:

56

answers:

3

How can I pass a string value by reference in javascript.

I want this kind of functionality.

    //Library.js
    function TryAppend(strMain,value)
    {
    strMain=strMain+value;
    return true;
    }

    //pager.aspx

    function validate()
    {
    str="Checking";
    TryAppend(str,"TextBox");
    alert(str); //expected result "Checking" TextBox
    //result being obtained "Checking"    
    }

How to do this. ?

+2  A: 

You cannot pass a value by reference in JS. You could create an object with a function to do this for you:

function TryAppend(originalValue) {

    // Holds the value to return
    this.Value = originalValue;

    // The function joins the two strings
    this.Append = function (append) { 
        this.Value+=append; 
        return true;
    }

}

You can then use this in any method as follows:

function AnyProcedure() {

    var str = "Checking";
    var append = new TryAppend(str);
    if (append.Append("TextBox")) {
        alert(append.Value);  // Will give "CheckingTextBox"
    }

}

Each time you call append, the Value string will be appended to. I.e.

If you then did:

append.Append(" Foo");

append.Value would equal CheckingTextBox Foo.

GenericTypeTea
@GenericTypeTea: How did you get strMain in myObject as myObject.strMain
Shantanu Gupta
@Generic: Will it work if both the functions are on different js files?
Shantanu Gupta
Yes. As long as both js files are references on the page they'll be able to see each other.
GenericTypeTea
+2  A: 

You need to return the String instead of true !!

    function TryAppend(strMain,value)  { 

    strMain=strMain+value; 

    return strMain; //you need return the  'String Value' to use in it another method

    } 


    //pager.aspx 


    function validate() { 

    str="Checking"; 

    str = TryAppend(str,"TextBox"); 

    alert(str); //expected result "Checking" TextBox 

    //result being obtained "Checking"     
    } 
Ninja Dude
@Samurai: I have some other purpose due to which i cannot return string
Shantanu Gupta
+1  A: 

Create a global variable (say gblstrMain) outside the function TryAppend and then set its value to strMain inside the function.

    var gblstrMain;

function TryAppend(strMain,value)
    {
    strMain=strMain+value;
    gblstrMain = strMain;
    return true;
    }

    //pager.aspx

    function validate()
    {
    str="Checking";
    TryAppend(str,"TextBox");
    str = gblstrMain;
    alert(str); //expected result "Checking" TextBox
    //result being obtained "Checking"    
    }

Since you are particular about "return true" in the TryAppend function, we can achieve by this workaround.

Vijey