Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 ?

like image 717
Andreas Grech Avatar asked Dec 03 '09 13:12

Andreas Grech


People also ask

Can you pass by pointer in JavaScript?

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).

Can I pass object as parameter JavaScript?

We can pass an object to a JavaScript function, but the arguments must have the same names as the Object property names.

Can I pass a value or a variable as a parameter in JavaScript?

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.

What is a pointer how is it used in parameter passing?

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.


1 Answers

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();
like image 119
moonshadow Avatar answered Oct 26 '22 21:10

moonshadow