JavaScript in Strict Mode

JavaScript code that runs in a browser can access a user’s private information. To protect this information, LockerService requires you to use ECMAScript (ES5) strict mode, and enforces it in your code. This mode makes it easier to write secure JavaScript. A few code tweaks to comply with ES5 can substantially reduce the need for checking data at runtime.

Here’s a simple example of how strict mode prevents JavaScript from traversing the call-stack and modifying other functions. Without strict mode, the following function would have returned the name of the function that called primaryFunction().

JavaScript code:
function primaryFunction() {
  ‘use strict’
  console.log(“The function calling the current method is: “+ primaryFunction.caller.name);
}
function callerFunction() {
  return primaryFunction(); 
}
callerFunction();

Output:
Uncaught TypeError: ‘caller’ and ‘arguments’ are restricted function properties and cannot be accessed in this context.
at primaryFunction (<anonymous>:3:72) at callerFunction (<anonymous>:6:10) at <anonymous>:8:1

Strict mode restricts access to several other entities. When it is enforced, you can no longer reference the window object through the JavaScript variable this, for example. These restrictions eliminate a lot of potential security vulnerabilities.

Leave a Reply