Reputation: 355
If I just put a 'this' at the beginning of JavaScript, it's not in any functions. Does 'this' have the same meaning with 'document'? or it means window?
Example:
$(this).ajaxComplete(handler);
In this case, do I attache the handler to the window or the document or something else?
Upvotes: 1
Views: 146
Reputation: 817128
If this is the only line in your script, then the code is evaluated in the global execution context. Lets have a look what the specification says about it:
10.4.1.1 Initial Global Execution Context
The following steps are performed to initialise a global execution context for ECMAScript code C:
- Set the VariableEnvironment to the Global Environment.
- Set the LexicalEnvironment to the Global Environment.
- Set the ThisBinding to the global object.
The ThisBinding
is the value that this
resolves. So, in the global context, this
refers to the global object, which is window
in browsers.
For more (less formal) information about this
, have a look at the MDN documentation.
Upvotes: 0
Reputation: 41
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
this
in the global context just references the global window
itself instead of the document. The above link has a great example:
console.log(this.document === document); // true
// In web browsers, the window object is also the global object:
console.log(this === window); // true
this.a = 37;
console.log(window.a); // 37
I haven't tested this in all browsers, but it appears to be true in both Firefox and Chrome.
Upvotes: 4
Reputation: 418
So it really depends where this code is. Is it in the $(document).ready() or $(window).load()? If you are just inside:
$(function(){ });
Then that is just short hand for $(document).ready(). So you'll be referring to the document. Check it out: http://learn.jquery.com/using-jquery-core/document-ready/
Also $(this) means you are referring to the current object.
Upvotes: 0