简体   繁体   English

为什么这个JavaScript代码段会返回true?

[英]Why does this JavaScript snippet return true?

Saw this example as a mental exercise. 把这个例子看作是一种心理锻炼。 I don't understand why it returns true. 我不明白为什么它返回true。 Surely the inner this should be scoped to the anonymous function and the outer this is not related to that function at all. 当然内this应该作用域的匿名函数和外this不涉及到功能都没有。

 var result = (function() { return this; }()) === this; var el = document.createElement("div") el.innerHTML = result; document.body.appendChild(el) 

There's not much scoping here, only "context". 这里没有太多的范围,只有“背景”。

As the IIFE is invoked without a context then the inner this defaults to window (except in ES5 "strict mode") that also being the default value of this in the global scope. 作为IIFE而不一个上下文中调用然后内this默认为window (除了在ES5“严格模式”),也正在的默认值this在全球范围内。

This question is not about scoping, but context. 这个问题不是范围界定,而是背景。

Context (ie this) in JS is normally set to be the object against which the function is invoked. JS中的Context(即this)通常被设置为调用函数的对象。

In this case no user defined object invokes the IIFE, so the context inside it defaults to the global object, hence true. 在这种情况下,没有用户定义的对象调用IIFE,因此其中的上下文默认为全局对象,因此为true。

Specifying strict mode will cause the context inside the IIFE to be undefined reducing the likelihood of accidental global object changes. 指定严格模式将导致IIFE内的上下文未定义,从而降低意外全局对象更改的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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