Fluidbyte
Fluidbyte

Reputation: 5210

JavaScript Global Object referencing vs 'this'

I'm working on an application framework written as an object literal and for the sake of simplicity I'd like to do two things:

  1. Have the object available globally
  2. Use the object name (as globally defined) for all references (vs. using this)

So, I've run some tests, done research, and am not finding any good reason NOT to take this approach. My question is - am I missing something? Perf tests actually seem to favor my method and from a logistical level I don't see any issues. Looking at other frameworks I've seen a mix, but I know that the this reference is revered by many programmers.

For reference...

A very minimal example of my approach:

var myobj = {

    someVal: 'foo',

    init: function(){
       // Make myobj available globally
       window.myobj = myobj;
       // Fire off a method
       myobj.doStuff();
    },

    doStuff: function(){
        // Just print out the contents...
        console.log(myobj.someVal);
    }
}

myobj.init(); 

Note the references are all to the global, not this.

Like I said, I've seen a mix of this, I guess I just would like to know if this could cause issues in the long-run or if this a much ado about nothing.

Upvotes: 2

Views: 71

Answers (1)

Ben McCormick
Ben McCormick

Reputation: 25718

As far as limitations go, the first thing that comes to mind is that you could only have one instance of this object. Trying to initialize a new one would wipe out the object.

Another reason for using this rather than a global variable name is that this will point to the correct object even if the name of the variable changes.

If you really want this to be a "create once" global object whose name never changes then this technique isn't technically wrong. But it won't be able to be used in any other situation. It is probably wiser to consider writing code that will be more adaptable if the requirements change (for instance if you use a library that causes a naming conflict with the chosen variable name)

Using this lets you be flexible in renaming the variable and passing it in different contexts without worrying about tracking variable names. It also will make it easy to change if naming conflicts arise.

Upvotes: 3

Related Questions