0

I've some scenarios where i need to pass value type as reference without changed the processing function.

  1. Example Numeric Types (var limit)

    var limit = 0; // Need to be the reference type
    var multiCallback = new MultiCallback(limit, function(){});
    for (element in myObject)
    {
     limit++;
     element.DoSomething(multiCallback.callback);
    }
    function MultiCallback(limit, func)
    {
     var calls = 0;
     function callback()
     {
     if (++calls == limit)
     {
     func();
     }
     }
     return {
     callback : callback
     }
    }
    
  2. Examble Function Types

    var resizeCallback = function(){};
    $(window).resize(resizeCallback);
    function showPage()
    {
     resizeCallback = resizePage();
    }
    function showLoader()
    {
     resizeCallback = resizeLoader();
    }
    

is there a solution

asked Jun 25, 2012 at 12:12
2
  • 1
    You can't (without changed the processing function...). Numbers and strings in JavaScript are immutable. Commented Jun 25, 2012 at 12:15
  • possible duplicate of Pass Variables by Reference in Javascript Commented Jun 25, 2012 at 13:10

2 Answers 2

1

Changing the value of a variable will never update the previous value of the variable.

For functions, you can do something like this:

var current = function() { ... };
function resizeCallback() {
 return current.apply(this, arguments);
}
// Updating current will work:
current = function() { ... something ... };

For other values (primitives and objects), the closest thing is to pass an object:

var limit = {value: 0};
function MultiCallback(limit, func) {
 ....
 if (limit.value == ++calls) ...
}
// Changing limit:
limit.value = 1;
answered Jun 25, 2012 at 12:16
Sign up to request clarification or add additional context in comments.

Comments

1

There is no pass by reference in javascript (assigning arguments is not visible to the caller). What you are doing in your function example is modifying a global variable.

You can wrap it with an object and mutations of that object are visible to the caller:

var limit = {
 value: 0 
};
answered Jun 25, 2012 at 12:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.