Home >Web Front-end >JS Tutorial >JavaScript starting point (in-depth understanding of strict mode)_Basic knowledge

JavaScript starting point (in-depth understanding of strict mode)_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:42:441105browse

Strict Mode is a new feature of ECMAScript5. Although ECMAScript5 is backward compatible with ECMAScript3, if strict mode is used, all ECMAScript3 syntax functions that are "no longer recommended" in ECMAScript5 will be overwritten, and a line will be thrown if they appear. Strict Mode was introduced to allow developers to choose a "better" version of Javascript that handles common and notorious errors differently. The latest versions of all major browsers - including IE10 and Opera12 - support strict mode. Most information about strict mode can be found on page 223 of the ES5 Specification [PDF].

How to enable strict mode
You can use strict mode globally or within a function scope. If you want to enable strict mode globally, just use the code in the first line of the program:

Copy code Code As follows:

'use strict';

To enable strict mode inside the function, you only need to use the code in the first line of the function body:
Copy code The code is as follows:

function imStrict(){
 'use strict';
// ...other code...
}

The statement that enables strict mode is just a plain string "use strict" without any new syntax. This means there won't be any negative impact on older browsers, so feel free to use it.

A practical application of enabling strict mode inside a function is to define the entire Javascript class library inside a strict mode function, so that external code is not affected:
Copy code The code is as follows:

(function(){
 "use strict";
 // Define your library strictly ...
})();

What does strict mode bring?
Before we start introducing special features, you need to remember that strict mode One of the goals is to allow faster debugging of errors. The best way to help developers debug is to throw errors when certain patterns occur, rather than failing silently or exhibiting strange behavior (which is why strict mode is no longer in use these days). Javascript under). Code in strict mode throws more error messages, which is a good thing because it helps developers quickly notice problems that must be solved immediately.

Remove the with statement (Eliminates with)
First of all, strict mode removes the with statement. When the with statement appears in strict mode, it is considered an illegal Javascript statement and throws a syntax error. So, the first step to using strict mode is to make sure you are not using with.
Copy code The code is as follows:

// Will cause a syntax error in strict mode
with(location){
alert(href);
}

Prevents accidental globals (Prevents accidental globals)
The second point is , variables must be declared before assignment. In non-strict mode, assigning a value to an undeclared variable will automatically generate a global variable with that name. This is one of the most common errors in Javascript. In strict mode, doing so will throw an error.
Copy code The code is as follows:

// Throw an error in strict mode
(function(){
someUndeclaredVar ="foo";
}());

Cancel the coercion of this value (Eliminates this coercion)
Another important change is that this value will no longer be cast to the global object when it is null or undefined. In other words, this retains its original value, which may cause errors in some code that relies on casts. For example:
Copy code The code is as follows:

window.color ="red";
function sayColor(){
// In strict mode, this will not point to window
alert(this.color);
}
// In the following two cases, both will be thrown in strict mode Error
sayColor();
sayColor.call(null);

Fundamentally, the this value must be assigned, otherwise the undefined value will remain. This means that omitting the new keyword when calling the constructor will also cause an error:
Copy code The code is as follows:

functionPerson(name){
this.name = name;
}
// Causes error in strict mode
var me =Person("Nicholas");

In this code, the new keyword is missing when calling the Person constructor, and the this value is undefined. Since you can't add properties to undefined, this code throws an error. In non-strict mode, this will be coerced into a global object, so the name attribute can be correctly assigned as a global variable.
No duplicates
When you do a lot of coding, it is easy to define duplicate attributes in objects or duplicate parameter names for functions. In strict mode, both situations will cause errors:
Copy code The code is as follows:

// Error in strict mode - Duplicate parameter
function doSomething(value1, value2, value1){
//code
}
// Error in strict mode - Duplicate attribute
var object ={
foo:"bar",
foo:"baz"
};

Both of these are syntax errors and will throw an error before the code is executed .
Safer eval()(Safer eval())
eval() has not been removed, but it has undergone some changes in strict mode. The biggest change is that variables and functions declared in the eval() statement will not be created in the containing scope. For example:
Copy code The code is as follows:

(function(){
eval( "var x = 10;");
// In non-strict mode, x is 10
// In strict mode, x is not declared and an error is thrown
alert(x);
}());

Any variables or functions created by eval() still stay in eval(). However, you can pass the value by returning a value from eval():
Copy code The code is as follows:

(function(){
var result =eval("var x = 10, y = 20; x y");
// Works normally in strict mode and non-strict mode Works (gets 30)
alert(result);
}());

Errors for immutables (Errors for immutables)
ECMAScript 5 also introduces the ability to modify property characteristics, such as setting a property to read-only or freezing an entire object's structure. In non-strict mode, attempts to modify an immutable property will fail silently. You may have encountered this kind of problem when using some native APIs. Strict mode will ensure that an error is thrown whenever you try to modify an object or an object's properties in a disallowed way.
Copy code The code is as follows:

var person ={};
Object.defineProperty (person,"name"{
writable:false,
value:"Nicholas"
});
// Will fail silently in non-strict mode, and throw an error in strict mode
person.name ="John";

In this example, the name attribute is set to read-only. In non-strict mode, assignment to name will fail silently; in strict mode, an error will be thrown.

Note: If you are using the ECMAScript attribute capabilities, I strongly recommend you to enable strict mode. If you're changing the mutability of objects, you're going to run into a bunch of errors that would be silently handled in non-strict mode.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn