Introduction to the

We all know that javascript is a weakly typed language. Prior to ES5, javascript programs were written in what I might call sloppy mode. For example, undefined variables can be used, arbitrary attributes can be assigned to objects without throwing exceptions, and so on.

In ES5, strict mode was introduced, which we can call strict mode. The corresponding sloppy mode can be called a non-strict mode.

Strict mode is not a subset of non-strict mode, but strict mode has some changes in semantics and non-strict mode, so we must pass strict testing in the process of use. To ensure that the execution of the program in strict mode is consistent with that in non-strict mode.

The use of Strict mode

Strict Mode changes the behavior of javascript in some ways, which we’ll cover in more detail in the next section.

So let’s see how we can use Strict mode.

Strict mode is mainly used in a complete script or function, not block {}. Using strict mode in blocks does not work.

Otherwise, the code in eval, the Function code, the Event Handler property, and the string passed to Windowtimers.setTimeout () can all be considered a complete script. We can use Strict mode here.

If strict mode is used in a script, you can add “use strict” to the top of the script:

// Strict mode for the entire script
'use strict';
var v = "Hi! I'm a strict mode script!";
Copy the code

We can also use strict mode in function:

function strict() {
  // Strict mode of the function
  'use strict';
  function nested() { return 'And so am I! '; }
  return "Hi! I'm a strict mode function! " + nested();
}
function notStrict() { return "I'm not strict."; }
Copy the code

If you’re using modules introduced in ES6, the default mode for modules is already strict, and we don’t need to use “use strict” :

function myModule() {
    // The default mode is strict
}
export default myModule;
Copy the code

New feature in Strict Mode

Strict Mode has some changes in syntax and runtime performance, as well as in non-strict mode, which we’ll look at next.

Force an exception

There are many cases in JS where an operation that could have been wrong was not thrown because of language features, resulting in a result that was not expected.

If strict mode is used, an exception is thrown directly.

For example, in strict mode, undefined global variables are not allowed:

'use strict';

globalVar = 10; //ReferenceError: globalVar is not defined
Copy the code

This can actually avoid the problem of writing variable names incorrectly by hand.

Let me look at some other examples:

'use strict';

// Assign to unwritable global variables,
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError

// Assign to unwritable attributes
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42.writable: false });
obj1.x = 9; // throws a TypeError

// Assign to a get method
var obj2 = { get x() { return 17; }}; obj2.x =5; // throws a TypeError

// Assign to an object that does not extend
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = 'ohai'; // throws a TypeError
Copy the code

Strict mode can restrict the deletion of non-deletable attributes, such as the constructor’s prototype:

'use strict';
delete Object.prototype; // throws a TypeError
Copy the code

Disallow duplicate attributes in object and function arguments:

'use strict';
var o = { p: 1.p: 2 }; // Duplicate declaration

function sum(a, a, c) { // Duplicate declaration
    'use strict';
    return a + a + c;
}
Copy the code

Disallow setting properties of base types:

(function() {
'use strict';

false.true = ' ';         // TypeError
(14).sailing = 'home';   // TypeError
'with'.you = 'far away'; // TypeError}) ();Copy the code

Simplify the use of variables

Using Strict mode simplifies variable use and makes your program code more readable.

First, strict mode disallows the use of with.

With is powerful, and we can influence the scope chain of variable lookups by passing objects to with. In other words, when we need to use an attribute in the with block, we will not only look up the existing scope chain, but also look up the object passed by the with.

with (expression)
  statement
Copy the code

We usually use with to simplify our code, such as:

var a, x, y;
var r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}
Copy the code

In the example above, PI is a variable in the Math object, but we can use it directly in the with block. It’s kind of like an import in Java.

The following example will show the problems with with:

function f(x, o) {
  with (o) {
    console.log(x); }}Copy the code

We print the x variable in the with block, and we can see from the code that f passes an x variable. But unexpected problems can arise if an object used by with also has an X attribute.

So, in strict mode, with is forbidden.

Then there are the changes to Eval.

In the traditional model, variables defined in Eval are automatically added to the scope that contains eval. Let’s look at an example:

var x = 17;
var evalX = eval("var x = 42; x;");
console.log(x);
Copy the code

Because a new variable x is introduced in Eval, the value of x overwrites the original definition of x=17. We end up with 42.

If use Strict is added, variables in eval are not added to the existing Scope, and we get result 17.

var x = 17;
var evalX = eval("'use strict'; var x = 42; x;");
console.log(x);
Copy the code

The benefit of doing this is to avoid eval impacting existing program logic.

Under strict mode, delete names are also not allowed:

'use strict';

var x;
delete x; / /!!!!!! syntax error

eval('var y; delete y; '); / /!!!!!! syntax error~~
Copy the code

To simplify the arguments

In Strict mode, arguments cannot be assigned as variable names:

'use strict';
arguments+ +;var obj = { set p(arguments) {}};try{}catch (arguments) {}function arguments() {}var f = new Function('arguments'."'use strict'; return 17;");
Copy the code

The above execution will report an error.

In addition, arguments are bound to named arguments in normal mode, and arguments[0] and arg change synchronously, both representing the first argument.

However, if in strict mode, arguments denotes the actual argument passed in.

Let’s take an example:

function f(a) {
    a = 42;
    return [a, arguments[0]];
}
var pair = f(17);
console.log(pair[0]);  / / 42
console.log(pair[1]);  / / 42
Copy the code

In the example above, arguments[0] is bound to the named argument a, and the value of arguments[0] ends up being 42 no matter what value f passes in.

In strict mode:

function f(a) {
    'use strict';
    a = 42;
    return [a, arguments[0]];
}
var pair = f(17);
console.log(pair[0]); / / 42
console.log(pair[1]);  / / 17
Copy the code

In this mode arguments[0] receives the actual passed argument, and we get result 17.

Arguments. callee is disabled in Strict mode. Normally arguments. Callee refers to the currently executing function, which prevents the virtual machine from optimizing inline, so it is forbidden in Strict mode.

Make javascript more secure

In normal mode, if we call this in a function f(), this refers to the global object. In strict mode, the value of this is undefined.

If we call it by call or apply, and we pass in a primitive value, in normal mode this will automatically point to its Box class (Object type for primitive type, Boolean, Number, etc.). If undefined and NULL are passed in, then this refers to the Global Object.

In strict mode, this refers to the value passed in and does no conversion or deformation.

The following values are true:

'use strict';
function fun() { return this; }
console.assert(fun() === undefined);
console.assert(fun.call(2) = = =2);
console.assert(fun.apply(null) = = =null);
console.assert(fun.call(undefined) = = =undefined);
console.assert(fun.bind(true) () = = =true);
Copy the code

Why is it safe? This means that, in strict mode, you cannot point to the window object through this, thus ensuring program security.

In addition, in normal mode, we can use fun.caller or fun.arguments to get function callers and arguments, which may access some private properties or unsafe variables, causing security problems.

Fun. caller or fun.arguments are forbidden in strict mode.

function restricted() {
  'use strict';
  restricted.caller;    // throws a TypeError
  restricted.arguments; // throws a TypeError
}
function privilegedInvoker() {
  return restricted();
}
privilegedInvoker();
Copy the code

Keep the keywords and functions in place

In strict mode, it is not allowed to use keywords as variable names in order to keep the JS standard going. These keywords include implements, interface, let, package, private, protected, public, static, and yield.

function package(protected) { / /!!!!!!
  'use strict';
  var implements; / /!!!!!!

  interface: / /!!!!!!
  while (true) {
    break interface; / /!!!!!!
  }

  function private() {}/ /!!!!!!
}
function fun(static) { 'use strict'; } / /!!!!!!
Copy the code

Function, on the other hand, can be anywhere in normal mode, but in strict mode, function can only be defined at the top of the script or inside the function:


'use strict';
if (true) {
  function f() {}/ /!!!!!! syntax error
  f();
}

for (var i = 0; i < 5; i++) {
  function f2() {}/ /!!!!!! syntax error
  f2();
}

function baz() { // kosher
  function eit() {}// also kosher
}
Copy the code

conclusion

Strict mode plays a very important role in the subsequent development of JS and the specification of existing programming mode. However, if we use it in the browser side, we still need to pay attention to the compatibility of the browser, and do a strict test.

Author: Flydean program stuff

Link to this article: www.flydean.com/js-use-stri…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!