When passing in a primitive type variable like a string or a number, the value is passed in by value. Passing in an object, however, is passed by reference. In this case, any property of that object is accessible within the function.
function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // 5
function objectchanger(func)
{
func.value = 6;
}
objectchanger(o);
alert(o.value); // 6
So what happens when you pass in a method of an object? Most would expect that it would be passed by reference allowing the method to access other parts of the object. Unfortunately, that is not the case. Check out this example:
function myobject()
{
this.value = 5;
}
myobject.prototype.add = function()
{
this.value++;
}
var o = new myobject();
alert(o.value); // 5
o.add();
alert(o.value); // 6
function objectchanger(fnc)
{
fnc(); // runs the function being passed in
}
objectchanger(o.add);
alert(o.value); // still just 6
The problem here is the use of 'this' keyword. It is a handy short-hand for referring to the current object context. When passing a function as a parameter, though, the context is lost. More accurately, 'this' now refers to the context of the object making the call instead of the object's function we just passed in. For standalone function, this would be the 'window' object and for functions called from an event, 'this' would be the event object.
If you don't know the name of the method ahead of time, then you will need to pass both the method and the object as parameters and use the call() method:
function objectchanger(fnc,obj)
{
fnc.call(obj); // run the method of the object being passed in
}
objectchanger(o.add,o);
alert(o.value); // 7
To pass a primitive type variable by reference, we can create an object like:
function integerHolder(num) {
this.integer = num;
}
and then pass a reference to an instance of integerHolder, where it could be modified.
Is there a simpler way to do this?





