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 ?
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 ?
Share Improve this question asked Dec 3, 2009 at 13:53 Andreas GrechAndreas Grech 108k101 gold badges303 silver badges362 bronze badges3 Answers
Reset to default 13You 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();
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();
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();