Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Strict mode

1. Concept:

Strict mode is a less restrictive variant of JavaScript. Strict schema is not a subset: it is semantically distinct from normal code.

Browsers that don’t support strict patterns also behave differently from those that do, so don’t use strict patterns without testing the strict pattern feature.

Strict mode can coexist with non-strict mode, so scripts can optionally add strict mode to primary key.

2, the purpose,

First, strict mode turns JavaScript traps into outright errors.

Second, strict fixes some errors that the engine is hard to optimize: the same code can sometimes be faster in strict mode than in non-strict mode.

Third, strict mode disables a syntax that may be defined in a future release.

3. Go into Strict mode

Strict mode is divided into global strict mode and function strict mode.

To enable strict mode in JavaScript, you need to define a string that will not be assigned to any variables before all the code:

"use strict"; // or 'use strict'
Copy the code

(1) Globally enable strict mode

// Enable global strict mode -- apply globally
'use strict'
// Define a variable a without the keyword var
 a = 1;
console.log(a);// The error message is a is not defined
Copy the code

(2) Function opens strict mode

function fun(){
    'use strict'
    // var v = 200; This sentence is correct in strict mode
    v = 200;
    console.log(v);
}
fun();V is not defined
Copy the code

I. Differences between different scenarios in strict mode (differences in variables)

1. Do not accidentally create variables

Accidental creation of global variables is not allowed in strict mode.

Example code is as follows:

    // Global strict mode is enabled, and variables v and w are defined in the wrong way
// 'use strict'
v = 100;
console.log(v);/ / 100

function fn() {
    // 'use strict' turns on local strict mode and defines variable w in the wrong way
    // define the local variable w
    w = 200;
    console.log(w);/ / 200
}
fn();
// Local variables defined in non-strict mode are automatically promoted by JavaScript to global variables.
// print w, which is 200
console.log(w);/ / 200
Copy the code

2. Silent failure becomes an exception

Translate a problem directly into an error (such as a syntax error or runtime error).

// Turn on strict mode to turn the problem into an error
'use strict'
const v = 100;//(define constant)
v = 1.14;// Reassign (as a variable)

console.log(v);
Copy the code

3. Disable the delete keyword

In strict mode, you cannot use the DELETE operator on variables.

(1) use the delete keyword on variables
// Enable strict mode
'use strict'

var v = 100;
delete v;// In non-strict mode: silent failure, no error reported and variable v deleted
console.log(v);/ / 100
// Delete of an unqualified identifier in strict mode.
Copy the code
(2) Use the delete keyword for arrays and method properties

Use the delete keyword on arrays and method properties in strict mode.

// Enable strict mode
'use strict'

// Delete the contents of the array in strict mode
var arr = [1.2.3.4]
delete arr[0];
console.log(arr);//[ <1 empty item>, 2, 3, 4 ]

// 2. Delete attribute in strict mode
var obj  =  {
    name : Pig Man
}
delete obj.name;
console.log(obj.name)//undefined
Copy the code

4. Restrictions on variable names

JavaScript also has restrictions on variable names in strict mode. In particular, do not use the following as variable names:

Example code is as follows:

// Enable strict mode
'use strict'
var static = 100;
console.log(static);/ / 100
Static can be used as a variable name in non-strict mode, but reserved words cannot be used in strict mode
Copy the code

Ii. Differences between different scenarios in strict mode (differences between objects)

1. Attributes that cannot be deleted

In strict mode, you cannot use the DELETE operator to delete non-deletable attributes.

// Enable strict mode
'use strict'
 delete Object.prototype; // You cannot delete the original properties of Object
console.log(Object.prototype);// In non-strict mode, the result will silently fail with the following result: {}.
// Delete will report an error in strict mode

// Strict mode is not perfect, and some JavaScript attributes can be removed
delete Math.random;
console.log(Math.random);// In strict mode: undefined
Copy the code

2. Attribute names must be unique

In strict mode, all attribute names within an object must be unique within the object.

Example code is as follows:

// Enable strict mode
'use strict';

// Object with attributes of the same name - editor error
var obj = {
    name:Pig Man.name:Incredibles
}
console.log(obj.name);
Copy the code

Note: editor error, running results do not report error. As shown below:

3. Assignment of read-only attributes

In strict mode, you cannot reassign a read-only property.

Example code is as follows:

'use strict'
var obj = {
    name:Pig Man
}
// Determines whether the specified property is read-only
var result = Object.getOwnPropertyDescriptor(obj,'name');
console.log(result);//{value: 64x, writable: true, Enumerable: true, different: true}
// Define the read-only property of the object obj
Object.defineProperty(obj,'age', {value:18.writable:false // Add the read-only age attribute.
});

// Modify the read-only attribute
obj.age = 80;
console.log(obj.age);// Silent failure occurs in non-strict mode, resulting in: 18

/ / using a try... The catch statement captures the hint
try{
obj.age = 80;
console.log(obj.age);// Silent failure occurs in non-strict mode, resulting in: 18
}catch (e) {
    console.log('This property cannot be modified')}Copy the code

4. Objects that are not extensible

In strict mode, you cannot add new properties or methods to non-extensible objects.

// Enable strict mode
'use strict'
var obj = function () {};// Set object obj to be an unextensible object
Object.preventExtensions(obj);
// Add attributes and methods to the object
// obj. Name = 'piggyback ';
// obj.age = 19;
obj.prototype.age = 10; // You can add new attributes to the object via stereotype attributes (when the object is a function)
console.log(obj.prototype);
Copy the code

3. Difference between different scenarios in strict mode (difference between function parameter names)

1. Parameter names must be unique

In strict mode, the parameters of a named function must be unique. Renaming parameters in strict mode is considered a syntax error.

Example code is as follows:

// Enable strict mode
'use strict'
function fun(a,a,b) {
    console.log(a+a+b);
}
// In strict mode, an error will be reported, and the parameter name is repeated
fun(2.3.4);/ / 10
Copy the code

2. Arguments are different

Arguments objects also behave differently in strict mode.

  • In non-strict mode, changing the value of the parameter is also reflected in the arguments object.
  • In strict mode, the form-participation arguments objects are completely independent.

Example code is as follows:

// Enable strict mode
'use strict'
function fun(value) {
    var value = Pig Man;
    console.log(value);// The nearest rule
    console.log(arguments[0]);
}
fun(Incredibles);// In non-strict mode, the arguments object takes values related to the parameter.
Copy the code

3,arguments.callee()

In strict mode, you cannot use the callee () method of arguments objects.

  • In non-strict mode, use the callee () method of the Arguments object to indicate the call to the function itself.
  • In strict mode, using the callee () method of the Arguments object results in an exception being thrown.

Example code is as follows:

'use strict'
function fun() {
    console.log(arguments.length);/ / 0
    Arguments' callee methods cannot be called in strict mode
    console.log(arguments.callee);
}
fun()
Copy the code

4. Limitations of function declarations

In strict mode, functions can only be declared in the global and function domains.

  • In non-strict mode, it is legal to declare functions anywhere.
  • In strict mode, it is an error syntax to declare functions except in the global and functional domains.

Example code is as follows:

// Enable strict mode
'use strict'

// in the global scope
function fn() {
    // in the function scope
    function n() {}}// In strict mode, functions can only be defined in global scope and function scope (functions cannot be defined in block scope)
for (var i=0; i<10; i++){New in ECMAScript 6 - block-level scopes exist
    var v = 100;
    function f() {// declare function in non-function scope, syntax error
        console.log('this is a function'); }}console.log(v);
f();
Copy the code

increaseevalscope

In strict mode, variables created using the eval () function can only be used inside the eval () function.

Example code is as follows:

'use strict'

eval('var x = 23');
console.log(x);// In strict mode, error is reported
Copy the code

Ban, speaking, reading and writing

In strict mode, eval () and arguments are forbidden as identifiers, and reading and writing their values is not allowed.

  • Using var declarations
  • Assign another value.
  • Try to modify the contained value.
  • Function name
  • Used as an argument to the named function
  • In the try… Used as an exception name in a catch statement.
"use strict"

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

Inhibition of this

  • Null or undefined values are converted to global objects when the apply () or call () methods of functions are used in non-strict mode.
  • In strict mode, the function’s this value is always the specified value (no matter what value).
// Enable strict mode
'use strict'
var v =100;
function fun() {
    console.log(this.v);
}
var obj = {
    v : 200
}
// fun.call(null); // In non-strict mode: 100, an error is reported in strict mode.
fun.call(obj)/ / 200
Copy the code