简体   繁体   中英

Why does this JavaScript snippet return true?

Saw this example as a mental exercise. I don't understand why it returns true. Surely the inner this should be scoped to the anonymous function and the outer this is not related to that function at all.

 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.

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.

In this case no user defined object invokes the IIFE, so the context inside it defaults to the global object, hence true.

Specifying strict mode will cause the context inside the IIFE to be undefined reducing the likelihood of accidental global object changes.

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