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
-
1You can't (without changed the processing function...). Numbers and strings in JavaScript are immutable.Matt– Matt2012年06月25日 12:15:27 +00:00Commented Jun 25, 2012 at 12:15
-
possible duplicate of Pass Variables by Reference in JavascriptFelix Kling– Felix Kling2012年06月25日 13:10:52 +00:00Commented Jun 25, 2012 at 13:10
2 Answers 2
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;
Comments
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
};