Reputation: 4862
I've some scenarios where i need to pass value type as reference without changed the processing function.
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
}
}
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
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
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