Take a look at the following code:
var o;
(function (p) {
p = function () {
alert('test');
};
})(o);
o(); // Error: 'o is not a function'
In the above function I am creating an anonymous function that takes one parameter, which self-invokes with a previously-created object passed as a parameter. Then I am pointing this object to a function (from inside the new scope) and ultimately (trying) to invoke it from outside.
My question is, how can I pass that argument 'by reference' as to change the pointer it points to ?
JavaScript, like most programming languages, strictly uses pass by value and does not support pass by reference, even though it does have what we call “references” (object references).
We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.
It's always pass by value (even when that value is a reference...). There's no way to alter the value held by a variable passed as a parameter, which would be possible if JavaScript supported passing by reference.
A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory items. Pointers are very useful for another type of parameter passing, usually referred to as Pass By Address. Pointers are essential for dynamic memory allocation.
You can achieve the effect you want by taking advantage of the fact that Javascript passes objects by reference:
var o = { };
(function (p) {
p.fn = function () {
alert('test');
};
})(o);
o.fn();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With