Search code examples
javascriptpass-by-referencejsplumb

Passing by reference in javascript


Hello all i am working with javascript and jsplumb library I am stuck in a problem and need help of experts.

Here is my scenario.

I have function in which i am using jsplumb library to create connection.

createlink = function (arg1, arg2 , con) {
  // doing some thing ;
    con = jsPlumb.connect({
             source: arg1,
             target: arg2
             });
 // doing some thing   
}

But the problem is that I want to access the same con created in the creatlink() function out side that function so what I did is

/*calling the function by passing the con as refrence*/
var con;
createlink("a", "b", con);
con.setParameter('name', "mycon"); // error as con is undefined

I have read that in JS objects can be passed as out param or pass by reference.

So what should be the correct and proper wayto access my con out side the function I don't want to return it as as this will create a separate copy.

Thanks any help will be appreciated.


Solution

  • You could return the connection object from the function:

    createlink = function (arg1, arg2) {
        return jsPlumb.connect({
            source: arg1,
            target: arg2
        });
    }
    
    var con = createlink("a", "b");