


The strict mode introduced in ECMAScript5 allows developers to have a "better" JavaScript language by allowing the JavaScript runtime environment to handle some of the most common and hard-to-find errors in the development process differently than currently. For a long time, I was skeptical about strict mode since only Firefox supported it. But today, all major browsers have supported strict mode in their latest versions (including IE10, Opera12 and Android4, IOS5). It is time to start using strict mode.
What role does strict mode play?
Strict mode introduces a lot of changes to JavaScript, and I divide them into two categories (obvious and subtle). The goal of minor improvements is to fix some detailed problems in current JavaScript, which I won't go into in depth here; if you are interested, please read the excellent document ECMA-262-5 in Detail Chapter 2 Strict Mode by Dmitry Soshnikov. I'll focus here on the obvious changes introduced by strict mode, the concepts you should know before using strict mode, and the changes that will help you the most.
Before you start learning specific features, please remember that one of the goals of strict mode is to allow you to debug faster and more conveniently. It is better for the runtime environment to explicitly throw an error when it detects a problem than to silently fail or behave strangely (as is often the case with JavaScript runtime environments that do not enable strict mode). Strict mode will throw more errors, but that's a good thing, because these errors will call your attention and fix many potential problems that were previously difficult to find.
Remove WITH keyword
First of all, the with statement is removed from strict mode. Code containing the with statement will throw an exception in strict mode. So the first step to using strict mode: Make sure you don’t use with in your code.
// The following JavaScript code will throw an error in strict mode
with (location) {
alert(href);
}
Prevent accidental assignment of global variables
Secondly, local variables must be declared before assigning a value. Before strict mode is enabled, copying an undeclared local variable will automatically create a global variable with the same name. This is one of the most common errors in Javascript programs, and an explicit exception will be thrown when trying to do this in strict mode.
// An exception will be thrown in strict mode
(function() {
SomeUndeclaredVar = "foo";
}());
THIS in the function no longer points to the global by default
Another important change in strict mode is that this in a function that is undefined or empty (null or undefined) no longer points to the global environment (global) by default. This will cause errors in the execution of some codes that rely on the default this behavior in functions, such as:
window.color = "red";
function sayColor() {
alert(this.color);
}
// An error will be reported in strict mode. If not in strict mode, "red"
will be prompted. sayColor();
// An error will be reported in strict mode. If not in strict mode, "red"
will be prompted. sayColor.call(null);
this will remain undefined until it is assigned, which means that when a constructor is executed, if there is no clear new keyword before, an exception will be thrown.
function Person(name) {
This.name = name;
}
//An error will be reported in strict mode
var me = Person("Nicholas");
In the above code, when the Person constructor is run, because there is no new before, this in the function will remain undefined. Since you cannot set properties for undefined, the above code will throw an error. In a non-strict mode environment, this that is not copied will point to the window global variable by default, and the result of the operation will be to accidentally set the name attribute for the window global variable.
Prevent duplicate names
When writing a lot of code, it is easy to accidentally set object properties and function parameters to a duplicate name. Strict mode will explicitly throw an error in this case
//Duplicate variable names will report an error in strict mode
function doSomething(value1, value2, value1) {
//code
}
//Duplicate object attribute names will report an error in strict mode:
var object = {
foo: "bar",
foo: "baz"
};
The above code will be considered a syntax error in strict mode and you will be prompted before execution.
Safe EVAL()
Although the eval() statement was not ultimately removed, some improvements were still made to it in strict mode. The biggest change is that variable and function declarations executed in eval() will not directly create corresponding variables or functions in the current scope, for example:
(function() {
eval("var x = 10;");
// In non-strict mode, alert 10
// In strict mode, an exception is thrown because x is not defined,
alert(x);
}());
Any variables or functions created during the execution of eval() are retained in eval(). But you can clearly obtain the execution result in eval() from the return value of the eval() statement, for example:
(function() {
var result = eval("var x = 10, y = 20; x y");
//The remaining statements can be run correctly in strict or non-strict mode. (resulst is 30)
alert(result);
}());
Exception thrown when modifying read-only properties
ECMAScript5 also introduces the ability to set specific properties of an object as read-only, or to make the entire object unmodifiable. But in non-strict mode, trying to modify a read-only property will fail silently. You are likely to encounter this situation when you are dealing with some browser native APIs. Strict mode will explicitly throw an exception in this case to remind you that modifying this property is not allowed.
var person = {};
Object.defineProperty(person, "name" {
writable: false,
Value: "Nicholas"
});
// In non-strict mode, silent failure occurs, in strict mode an exception is thrown.
person.name = "John";
In the above example, the name attribute is set to read-only. Modifying the name attribute in non-strict mode will not cause an error, but the modification will not be successful. But strict mode will explicitly throw an exception.
NOTE: It is strongly recommended that you enable strict mode when using any ECMAScript property attribute specification.
How to use?
It is very easy to turn on strict mode in modern browsers, just enter the following command in the JavaScript code
"use strict";
Although it seems that the above code is just a string that is not assigned to a variable, it actually instructs the JavaScript engine to switch to strict mode (browsers that do not support strict mode will ignore the above code and will not any impact on subsequent execution). Although you can apply this directive globally or in a certain function, you still have to be reminded not to enable strict mode in the global environment.
// Please don’t use it like this
"use strict";
function doSomething() {
// This part of the code will run in strict mode
}
function doSomethingElse() {
// This part of the code will also run in strict mode
}
Although the above code doesn't seem like a big problem. But when you are not responsible for maintaining all the code introduced in the page, using strict mode in this way will expose you to problems caused by third-party code that is not prepared for strict mode.
Therefore, it is best to apply the instruction to enable strict mode in the function, for example:
function doSomething() {
"use strict";
//The code in this function will run in strict mode
}
function doSomethingElse() {
//The code in this function will not run in strict mode
}
If you want strict mode to be enabled in more than one function, use an immediately-invoked function expression (IIFE):
(function() {
"use strict";
Function doSomething() {
// This function runs in strict mode
}
Function doSomethingElse() {
// This function also runs in strict mode
}
}());
Conclusion
I strongly recommend that you enable JavaScript strict mode from now on, it can help you find unnoticed errors in your code. Don't enable it globally, but you can use IIFE (immediate execution of function expressions) as much as possible to apply strict mode to multiple function scopes. At the beginning, you will encounter error messages that you have not encountered before. This is normal. When enabling strict mode, be sure to test in supported browsers to identify new potential issues. Don't just add a "use strict" line to your code and assume the rest of the code will work. Finally, start writing better code in strict mode.
Note:
Here is a summary of strict mode support in various browsers.
You can test the current browser's strict mode support on this page.
Advantages of strict mode:
Make JavaScript stronger
1. This is no longer encapsulated. In normal mode, this is always an object.
2. Fun.caller and fun.arguments are not attributes that can be deleted, nor can they be set or retrieved.
3. Arguments.caller is also an attribute that cannot be deleted, nor can it be set or retrieved.
Paves the way for future ECMAScript versions
1. The following reserved words have been added: implements, interface, let, package, private, protected, public, static and yield.
2. Method declaration should be placed at the front of the script or method, not in the middle of statements such as if or for.

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
