views:

88

answers:

3

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 ?

+5  A: 

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();
moonshadow
Actually, "pass by reference" is a bit of a misnomer in JavaScript. Relative to other languages that have true "reference" types, JavaScript does *not* pass anything by reference. It always passes by value. That value may *hold* a reference, which is what I think you're trying to say.
Crescent Fresh
A: 

When you pass in variable o in your example, you're passing an undefined value, not a reference to anything. What you'd need to do, is send the objects parent. In this case, the window object (assuming you're using a browser).

(function (p, name) {
    p[name] = function() {
       alert('test');
    };
})(window, "o");
o();

This passes in the window object, and the name of your new function. Then it assigns your function to the window, and it now available to be called. Unless you're going to use closures, though, I'd suggest just assigning the function directly.

function o() {
    alert('test');
};
o();
MillsJROSS
+2  A: 

You're better off using the language as intended rather than trying to bend it to fit idioms that only make sense in a language constructed according to a different set of principles.

var o = (function(p) {
    return function() {
        alert('test');
    };
})();

o();
NickFitz
The reason I will be using the above idiom is because with that, if I want to change the name of the main object (`o`), I only have to change it from the 1st line (`var o;`) and from the part where I pass it as a parameter (`})(o);`); I won't need to change anything from the anonymous function.
Andreas Grech