Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  191] [ 7]  / answers: 1 / hits: 39523  / 13 Years ago, tue, june 14, 2011, 12:00:00

I'm reading the Backbone.js documents and am seeing a lot of code that assigns attributes to the window object:


window.something = "whatever";

What's the difference between calling this code, and just assigning the variable and creating a global variable, like this:


something = "whatever";

I assume there is some kind of scope difference, and/or object ownership difference (window being the owner vs. not), but I am interested in the detail between the two and why I would use window vs. not use it.


More From » attributes

 Answers
15

No difference. They both have the same effect (In the browser, where window is the global context1).




  • window.foo = bar sets the property foo on window.

  • foo = bar indicates either a typo or intentionally global.



Since I have to double check whether it's a typo or not, I personally find it more readable to set window.foo directly.



Also, in ES5 strict mode, foo = bar is an illegal assignment because foo is not declared and will throw a Error.



Edit:



As noted in the comments, foo = bar will look all the way up the scope chain for the variable foo and re-assign it with bar if it's found. If it's not found, it will create a new global variable.



Also with window.foo = bar you're just assigning a property to an object, which can be deleted using delete window.foo.



In ES5 strict mode it is invalid to delete a variable.






1 In other environments, such as node.js and Web Workers, there may be another name for the global object and window may not exist at all. Node.js uses global and Web Workers use self.


[#91709] Monday, June 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
larrycodys

Total Points: 394
Total Questions: 93
Total Answers: 78

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;