COERCION OF THIS
One of the biggest security issues, and indeed one of the most confusing aspects of JavaScript, is how the value of this
is coerced in certain situations. When using the apply()
or call()
methods of a function, a null
or undefined
value is coerced to the global object in nonstrict mode. In strict mode, the this
value for a function is always used as specified, regardless of the value. For example:
// Access a property
// Non-strict mode: Accesses the global property
// Strict mode: Throws an error because this is null
let color = "red";
function displayColor() {
alert(this.color);
}
displayColor.call(null);
This code passes null to displayColor.call()
, which in nonstrict mode means the this
value of the function is the global object. The result is an alert displaying "red"
. In strict mode, the this
value of the function is null
, so it throws an error when attempting to access a property of a null
object.
Typically, functions will coerce their this...