[英]What 'this' means in javascript?
If I just put a 'this' at the beginning of JavaScript, it's not in any functions. 如果我只是在JavaScript的开头放置一个“ this”,则它不在任何函数中。 Does 'this' have the same meaning with 'document'?
“ this”与“ 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 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this
this
in the global context just references the global window
itself instead of the document. this
在全球范围内只引用全局window
本身,而不是文件。 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. 我尚未在所有浏览器中都进行过此测试,但是在Firefox和Chrome中似乎都是如此。
So it really depends where this code is. 因此,这实际上取决于此代码在哪里。 Is it in the $(document).ready() or $(window).load()?
是在$(document).ready()还是$(window).load()中? If you are just inside:
如果您只是在里面:
$(function(){ });
Then that is just short hand for $(document).ready(). 这只是$(document).ready()的简写。 So you'll be referring to the document.
因此,您将参考该文档。 Check it out: http://learn.jquery.com/using-jquery-core/document-ready/
签出: http : //learn.jquery.com/using-jquery-core/document-ready/
Also $(this) means you are referring to the current object. $(this)也表示您正在引用当前对象。
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
10.4.1.1初始全局执行上下文
The following steps are performed to initialise a global execution context for ECMAScript code C :
执行以下步骤来初始化ECMAScript代码C的全局执行上下文:
- Set the VariableEnvironment to the Global Environment .
将VariableEnvironment设置为全局环境 。
- Set the LexicalEnvironment to the Global Environment .
将词汇环境设置为全球环境 。
- Set the ThisBinding to the global object.
将ThisBinding设置为全局对象。
The ThisBinding
is the value that this
resolves. ThisBinding
是this
解析的值。 So, in the global context, this
refers to the global object, which is window
in browsers. 因此,在全局上下文中,
this
是指全局对象,它是浏览器中的window
。
For more (less formal) information about this
, have a look at the MDN documentation . 有关更多的(不太正式的)信息
this
,看看在MDN文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.