简体   繁体   中英

What 'this' means in javascript?

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?

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.

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.

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 :

  1. Set the VariableEnvironment to the Global Environment .
  2. Set the LexicalEnvironment to the Global Environment .
  3. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM