MR.ABC
MR.ABC

Reputation: 4862

Javascript, value types as reference

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

Upvotes: 0

Views: 375

Answers (2)

Esailija
Esailija

Reputation: 140236

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 
};

Upvotes: 1

Rob W
Rob W

Reputation: 349232

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;

Upvotes: 1

Related Questions