3

When I open jQuery's source code I find this line.

var 
// Will speed up references to window, and allows munging its name.
window = this

Why and how this line will speed up?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
David
  • 133
  • 5

2 Answers2

13
  1. javascript functions have lexical scope
  2. jQuery wraps its entire implementation in an anonymous function
  3. when said function begins execution it is executing in the "global" scope (ie this == window).

"window = this;" simply creates a local identifier in that scope so that references to it do not have to "bubble up" outside of the local scope to resolve.

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • Thanks. I just noticed that the code's running in a function scope. (function(){var window=this;...})(); – David Feb 19 '09 at 06:44
0

this would be faster for javascript to reference to, as compared to window which would have to be resolved to the window object.

Ali
  • 261,656
  • 265
  • 575
  • 769