Alex
Alex

Reputation: 5724

Passing around references in JS inside a function

In the following code, I am passing

(function(Index){
    Index.Index = function(){console.log(23)};

    Index = function(){console.log(123)};


}(Window.Index = Window.Index || {}));    

Yet the return I am getting is Window.Index={Index:function...}

Which logs 23.

I am -trying- to get it to be re-declared as a function. eg expected value should be:

Window.Index = function(){console.log(123)};

What am I doing wrong?

Upvotes: 3

Views: 75

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382132

The variable you get in you function is a reference to the Index object, not to the variable containing this reference. In javascript, arguments are always passed by value, even if those values are references in the case of objects.

Solutions would be

1) to pass window (that is the object holding the Index property)

(function(holder){
    holder.Index = function(){console.log(123)};
})(window);

2) to directly change window.Index :

(function(){
    window.Index = function(){console.log(123)}; // or omit 'window', that's the same
})();

3) to pass the name of the property :

(function(holder, propname){
    holder[propname] = function(){console.log(123)};
})(window, "Index");

4) to pass a callback :

(function(callback){
    var Index = function(){console.log(123)};
    callback(Index);
})(function(v){window.Index=v});

Note that you're basically using the common module pattern.

Upvotes: 1

Related Questions