I've been trying to understand how "use strict"
helps in creating secure web applications.
Reading this excerpt from MDN regarding "use strict"
:
Strict mode makes it easier to write "secure" JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user's private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality.
First, the value passed as
this
to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function,this
is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or numberthis
; or the global object if called with anundefined
ornull
this
. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specifiedthis
is not boxed into an object, and if unspecified, this will be undefined.
So as far as i understand, this talks about avoiding the very common XSS
attack by not allowing any user script to access the global window object using this
(gives undefined
for any regular function call):
(function() {"use strict"
alert(this) //undefined
alert(window) //global window object
})()
However can't we just access the same using the window
object in any script (like alert(window)
in above code? Would this be somehow not allowed during runtime? What's the thing i'm missing here?