Passing a parameter as a pointer in JavaScript

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 create an anonymous function that takes one parameter, which itself calls the previously created object passed as a parameter. Then I point this object to a function (from inside a new area) and ultimately (try) to call it from the outside.

My question is, how do I pass this argument โ€œby referenceโ€ to change the pointer it points to?

+6
javascript pointers
source share
3 answers

You can achieve the desired effect, taking advantage of the fact that Javascript passes objects by reference:

 var o = { }; (function (p) { p.fn = function () { alert('test'); }; })(o); o.fn(); 
+12
source share

You better use the language for its intended purpose, rather than trying to bend it so that it matches idioms that only make sense in a language built in accordance with a different set of principles.

 var o = (function(p) { return function() { alert('test'); }; })(); o(); 
+3
source share

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

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

This is passed in the window object and the name of your new function. Then it assigns your function to the window, and now it is available for calling. However, if you intend to use closure, I would suggest simply assigning the function directly.

 function o() { alert('test'); }; o(); 
+1
source share

All Articles