Ben A.
Ben A.

Reputation: 32

Invoking a function globally within another function

I tried this and it seems to work, however I want to know if it is valid code and will be ok with all browsers. I basically want to invoke a function as a global object, only in the case that the user is logged in. It is important that the created object remains in the global scope. So I tried:

var specialStuff; // defined globally

then some Ajax code within "myMainObject" that calls this.involeSpecialStuff(); if the user is logged-in:

myMainObject.prototype.invokeSpecialStuff = function(){
    document.specialStuff = new specialStuff({foo:bar});
});

The focus of my question is on the "document.specialStuff" part, and if it is the right way to access the globally pre-defined empty "specialStuff" variable, as opposed to "specialStuff = new specialStuff()", which causes "TypeError: undefined is not a constructor (evaluating 'new specialStuff({foo:bar});"

Thanks

Upvotes: 0

Views: 46

Answers (2)

leo.fcx
leo.fcx

Reputation: 6467

Considering the explanation you gave and specialStuff is a global var which references to a function (class), You cannot do specialStuff = new specialStuff(); since you are overriding the same value with a new instance from specialStuff class. It will work the first time but the next time indeed it is going to trigger the error you mentioned.

You don't need either to use document.specialStuff (although it works). You can simple use another variable for it as follows:

myMainObject.prototype.invokeSpecialStuff = function(){
    var mySpecialStuff = new specialStuff({foo:bar});
});

EDIT:

This could be a complete example:

// Defining you class in 'global context'
// Since it is called as a constructor below, it should be a function
var specialSuff = function(args){
    // Do your constructor stuff here
};

// Defining a variable which is going to hold an instance of specialStuff
var mySpecialStuff;

myMainObject.prototype.invokeSpecialStuff = function(){
    // Creating an instance of specialStuff 
    mySpecialStuff = new specialStuff({foo:bar});
});

Upvotes: 1

qzcx
qzcx

Reputation: 371

You shouldn't need the document part in order to store a global variable in javascript. Probable better to just do

specialStuff = new specialStuff({foo:bar});

Of course, I always will question whether you really need this global function. Globals are always something to avoid in most cases.

Upvotes: 0

Related Questions