`this` in global scope in ECMAScript 6

烂漫一生 提交于 2019-12-05 12:16:57

Yes, this in global scope will continue to refer to the global object in ES6. (Generally, ES6 is supposed to be fully backwards compatible, i.e. any code that was guaranteed to work in ES5 should also work in ES6).

The notion of "global scope", however, will no longer be identical with the global object in ES6. It introduces new declaration forms that are lexically scoped (let, const, class, module, and a few more). The conclusion at the last meeting was that none of these will appear as properties of the global object. There is a variety of technical and methodological reasons for that, but the bottom line is that it is best to avoid using the global object directly altogether (this has always been true, but is even more so in ES6).

Is there something specific you need the global object for?

Mostly yes.

Passing this in any non-object (or non-set this) will refer to the global object:

(function( global ){ /* do stuff! */ }(this));

This behavior is intended to stay in ES6 (for understandable backward compatibility issues). And that's how most of multiplatform (Browser/Node) plugins I know of are accessing the global object. For example: https://github.com/documentcloud/underscore/blob/master/underscore.js#L12

Although, it's true that plugin on the server only access this as being module (which is exported). But, that's what you want in node. Your global space isn't cleaned up ever (except if done manually, or on server restart). So it's shared between all client connections; assigning anything to the global space is really not a good idea.


The only notable difference in how this is handled between javascript "version" is in strict mode, where it will throw an error is if null or undefined is passed to call or apply or bind (in the position of the this value). In un-strict mode, this was only coerced to the global object.

"use strict";
foo.apply(null); // Throw error

Hope this help!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!