honestbleeps / BabelExt

BabelExt is a cross browser boilerplate/library for extension development
http://babelext.com/
MIT License
227 stars 36 forks source link

Not sure about `var instance = this;` #6

Closed OpenGG closed 11 years ago

OpenGG commented 12 years ago
var BabelExt = (function() {
  // define private variables here...
  var instance   = this;

  instance.detectedBrowser = '';

Here why do you use this? I know browsers all have some kind of sandbox and you can access the real window this way, but then I browse your code and can't find anything relies on window, so why not use var instance = {}; ?

honestbleeps commented 11 years ago

Sorry for the very slow reply, I've been insanely busy and haven't been able to tend to hobby projects like this one...

instance = this has nothing to do with accessing "window", but rather the BabelExt object.. mostly a bit of a shortcut / safety net for scope issues and to be 100% honest kind of a lazy one to avoid needing to think as carefully about scope.

http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this

i just used instance instead of self.

OpenGG commented 11 years ago

I know this can be used to referred to an instance of a constructor function, but only when this constructor function is called by new Some();, or new Note(); in your referring case.

But what's happening in BabelExt.js is another case:

var BabelExt = (function() { // define private variables here... var instance = this; console.log(this.window===window); // I think the result is true; )}()

The function containing this is called right away, without new, and so this.window===window will be true.