Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to turn on the strict mode of JavaScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "how to open the strict mode of JavaScript", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to open the strict mode of JavaScript" article.

1. Strict mode

In addition to normal mode, JavaScript also provides strict mode.

The strict mode of ES5 is a way of using restricted JavaScript variants, that is, running JS code under strict conditions

Strict mode will only be supported in browsers above IE10, while older browsers will be ignored.

Strict mode makes some changes to the normal JavaScript semantics:

Some unreasonable and imprecise aspects of Javascript syntax are eliminated, and some strange behaviors are reduced.

Eliminate some unsafe places in the running of the code and ensure the safety of the running of the code.

Improve compiler efficiency and increase running speed

Disable some syntax that may be defined in future versions of ECMAScript, laying the groundwork for a future version of Javascript. For example, some reserved words such as class, enum, export, extends, import, super cannot be variable names.

1.1. Turn on strict mode

Strict mode can be applied to entire scripts or individual functions.

Therefore, when using it, we can divide strict mode into two cases: turn on strict mode for script and turn on strict mode for function.

1.1.2. Turn on strict mode for scripts

To turn on strict mode for the entire script file, you need to put a specific statement before all statements

"use strict" or "use strict'"

User strict'; console.log ("this is strict mode.")

Because "use strict" is in quotation marks, older browsers ignored it as if it were an ordinary string.

Some script is basically in strict mode, and some script scripts are in normal mode, which is not good for file merging, so you can put the entire script file in an anonymous function that executes immediately. This creates a scope independently without affecting other script script files.

(function () {'use strict'; var num = 10; function fn () {}}) (); 1.1.2. Turn on strict mode for the function

To turn on strict mode for a function, you need to put the "use strict" or 'use strict' declaration before all statements in the body of the function

The js code below 'use strict'; / / will execute the code in strict mode (function () {' use strict';}) (); / / just turn on strict mode function fn () {'use strict' for the fn function at this time / / the following code executes in strict mode} function fun () {/ / or normal mode}

If you place "use strict" on the first line of the function body, the entire function runs in strict mode.

2. Changes in strict mode

Strict mode has made some changes to the syntax and behavior of JavaScript.

2.1. Variable regulation

In normal mode, if a variable is assigned without a declaration, the default is a global variable

Strict mode forbids this use, and variables must be declared with the var command before using the

It is forbidden to delete declared variables. For example, ``delete x` syntax is incorrect.

'use strict'; / / 1. Our variable name must be declared before using / / num = 10; / / console.log (num); var num = 10; console.log (num); / / 2. We can't delete the declared variable / / delete num; 2.2 at will. This points to the problem in strict mode.

The previous this in the global scope function points to the window object

The this in the global scope function in strict mode is undefined

Previously, the constructor can be called without adding new. When an ordinary function, this points to the global object.

In strict mode, if the constructor does not add a new call, this points to undefined. If you assign a value to it, an error will be reported.

The constructor instantiated by new points to the created object instance

Timer this still points to window

Event, object, or point to the caller

'use strict'; / / 3. In strict mode, the this in the global scope function is undefined. Function fn () {console.log (this); / / undefined. } fn () / / 4. In strict mode, if the constructor does not add a new call, this points to undefined. If it is assigned to him, it will report an error. Function Star () {this.sex = 'male';} / / Star (); var ldh = new Star (); console.log (ldh.sex); / / 5. Timer this also points to window setTimeout (function () {console.log (this);}, 2000)

Function cannot have parameters with duplicate names

The function must be declared at the top level, and the new version of JavaScript will introduce "block-level scope" (already introduced in ES6). To be in line with the new version, it is not allowed to declare a function within a non-function block of code

'use strict'; / / 6. Parameters in functions in strict mode are not allowed to have duplicate names function fn (a, a) {console.log (a + a);}; / / fn (1,2); function fn () {} 3, higher-order functions

A higher-order function is a function that operates on other functions, receiving a function as an argument or outputting a function as a return value

Receive function as parameter

/ / higher-order functions-functions can be passed as arguments to function fn (a, b, callback) {console.log (a + b); callback & & callback ();} fn (1,2, function () {console.log ('I am the last called');})

Use the function as the return value

Function fn () {return function () {}}

In this case, fn is a function of higher order.

A function is also a data type, which can also be passed as a parameter to another parameter. The most typical one is as a callback function.

The same function can also be passed back as a return value.

4. Closure 4.1, variable scope

Variables are divided into two types according to their scope: global variables and local variables.

Global variables can be used inside the function

Local variables cannot be used outside the function

When the function is finished, the local variables in the scope are destroyed.

4.2. What is a closure

A closure is a function that has access to variables in the scope of another function.

Simple understanding: one scope can access local variables inside another function

/ / closure is a function that has access to variables in the scope of another function. / / closure: our fn2 function scope accesses the local variable num function fn1 () {/ / fn1 in another function fn1, that is, the closure function var num = 10; function fn2 () {console.log (num); / / 10} fn2 () } fn1 (); 4.3.Debug closures in chrome

Open a browser and press F12 to start the chrome debugging tool.

Set breakpoints.

Find the Scope option (meaning Scope scope).

When we refresh the page, we will enter breakpoint debugging, and there will be two parameters in Scope (global global scope and local local scope).

When fn2 () is executed, there is an extra Closure parameter in the Scope, which indicates that a closure is generated.

4.4. The function of closures

Extend the scope of a variable

/ / closure is a function that has access to variables in the scope of another function. / / one scope can access the local variable of another function / / the scope outside our fn can access the local variable inside the fn / / the main function of the closure: extend the scope of the variable function fn () {var num = 10; return function () {console.log (num) }} var f = fn (); f (); 4.5, closure exercise 4.5.1, click li output index number durian stinky tofu herring canned pig's feet / / closure application-click li to output the current li index number / / 1. We can add attributes dynamically by var lis = document.querySelector ('.nav'). QuerySelectorAll ('li'); for (var I = 0; I)

< lis.length; i++) { lis[i].index = i; lis[i].onclick = function() { // console.log(i); console.log(this.index); } } // 2. 利用闭包的方式得到当前小li 的索引号 for (var i = 0; i < lis.length; i++) { // 利用for循环创建了4个立即执行函数 // 立即执行函数也成为小闭包因为立即执行函数里面的任何一个函数都可以使用它的i这变量 (function(i) { // console.log(i); lis[i].onclick = function() { console.log(i); } })(i); } 4.5.2、定时器中的闭包 榴莲 臭豆腐 鲱鱼罐头 大猪蹄子 // 闭包应用-3秒钟之后,打印所有li元素的内容 var lis = document.querySelector('.nav').querySelectorAll('li'); for (var i = 0; i < lis.length; i++) { (function(i) { setTimeout(function() { console.log(lis[i][xss_clean]); }, 3000) })(i); } 5、递归 如果一个函数在内部可以调用其本身,那么这个函数就是递归函数 简单理解: 函数内部自己调用自己,这个函数就是递归函数 由于递归很容易发生"栈溢出"错误,所以必须要加退出条件 return // 递归函数 : 函数内部自己调用自己, 这个函数就是递归函数 var num = 1; function fn() { console.log('我要打印6句话'); if (num == 6) { return; // 递归里面必须加退出条件 } num++; fn(); } fn(); 6、浅拷贝和深拷贝 浅拷贝只是拷贝一层,更深层次对象级别的只拷贝引用 深拷贝拷贝多层,每一级别的数据都会拷贝 Object.assign(target,....sources) ES6新增方法可以浅拷贝 6.1、浅拷贝// 浅拷贝只是拷贝一层,更深层次对象级别的只拷贝引用var obj = { id: 1, name: 'andy', msg: { age: 18 }};var o = {}for(var k in obj){ // k是属性名,obj[k]是属性值 o[k] = obj.[k];}console.log(o);// 浅拷贝语法糖Object.assign(o,obj);6.2、深拷贝// 深拷贝拷贝多层,每一级别的数据都会拷贝var obj = { id: 1, name: 'andy', msg: { age: 18 } color: ['pink','red']};var o = {};// 封装函数function deepCopy(newobj,oldobj){ for(var k in oldobj){ // 判断属性值属于简单数据类型还是复杂数据类型 // 1.获取属性值 oldobj[k] var item = obldobj[k]; // 2.判断这个值是否是数组 if(item instanceof Array){ newobj[k] = []; deepCopy(newobj[k],item) }else if (item instanceof Object){ // 3.判断这个值是否是对象 newobj[k] = {}; deepCopy(newobj[k],item) }else { // 4.属于简单数据类型 newobj[k] = item; } }}deepCopy(o,obj);7、 正则表达式 正则表达式是用于匹配字符串中字符组合的模式。在JavaScript中,正则表达式也是对象。 正则表通常被用来检索、替换那些符合某个模式(规则)的文本,例如验证表单:用户名表单只能输入英文字母、数字或者下划线, 昵称输入框中可以输入中文(匹配)。此外,正则表达式还常用于过滤掉页面内容中的一些敏感词(替换),或从字符串中获取我们想要的特定部分(提取)等 。 7.1、特点 实际开发,一般都是直接复制写好的正则表达式 但是要求会使用正则表达式并且根据自身实际情况修改正则表达式 7.2、创建正则表达式 在JavaScript中,可以通过两种方式创建正则表达式 通过调用 RegExp 对象的构造函数创建 通过字面量创建 7.2.1、通过调用 RegExp 对象的构造函数创建 通过调用 RegExp 对象的构造函数创建 var 变量名 = new RegExp(/表达式/);7.2.2、通过字面量创建 通过字面量创建 var 变量名 = /表达式/; 注释中间放表达式就是正则字面量 7.2.3、测试正则表达式 test test()正则对象方法,用于检测字符串是否符合该规则,该对象会返回true或false,其参数是测试字符串 regexObj.test(str) regexObj 写的是正则表达式 str 我们要测试的文本 就是检测str文本是否符合我们写的正则表达式规范 示例 // 正则表达式在js中的使用 // 1. 利用 RegExp对象来创建 正则表达式 var regexp = new RegExp(/123/); console.log(regexp); // 2. 利用字面量创建 正则表达式 var rg = /123/; // 3.test 方法用来检测字符串是否符合正则表达式要求的规范 console.log(rg.test(123)); console.log(rg.test('abc')); 7.3、正则表达式中的特殊在字符7.3.1、边界符 正则表达式中的边界符(位置符)用来提示字符所处的位置,主要有两个字符 边界符说明^表示匹配行首的文本(以谁开始)$表示匹配行尾的文本(以谁结束) 如果^ 和 $ 在一起,表示必须是精确匹配 // 边界符 ^ $var rg = /abc/; //正则表达式里面不需要加引号,不管是数字型还是字符串型// /abc/只要包含有abc这个字符串返回的都是trueconsole.log(rg.test('abc'));console.log(rg.test('abcd'));console.log(rg.test('aabcd'));var reg = /^abc/;console.log(reg.test('abc')); //trueconsole.log(reg.test('abcd')); // trueconsole.log(reg.test('aabcd')); // falsevar reg1 = /^abc$/// 以abc开头,以abc结尾,必须是abc7.3.2、字符类 字符类表示有一系列字符可供选择,只要匹配其中一个就可以了 所有可供选择的字符都放在方括号内 ①[] 方括号/[abc]/.test('andy'); // true 后面的字符串只要包含 abc 中任意一个字符,都返回true ②[-]方括号内部 范围符/^[a-z]$/.test() 方括号内部加上-表示范围,这里表示a - z26个英文字母都可以 ③[^] 方括号内部 取反符 ^/[^abc]/.test('andy') // false 方括号内部加上^表示取反,只要包含方括号内的字符,都返回 false 注意和边界符 ^ 区别,边界符写到方括号外面 ④字符组合/[a-z1-9]/.test('andy') // true 方括号内部可以使用字符组合,这里表示包含a 到 z的26个英文字母和1到9的数字都可以 //var rg = /abc/; 只要包含abc就可以 // 字符类: [] 表示有一系列字符可供选择,只要匹配其中一个就可以了 var rg = /[abc]/; // 只要包含有a 或者 包含有b 或者包含有c 都返回为true console.log(rg.test('andy')); console.log(rg.test('baby')); console.log(rg.test('color')); console.log(rg.test('red')); var rg1 = /^[abc]$/; // 三选一 只有是a 或者是 b 或者是c 这三个字母才返回 true console.log(rg1.test('aa')); console.log(rg1.test('a')); console.log(rg1.test('b')); console.log(rg1.test('c')); console.log(rg1.test('abc')); console.log('------------------'); var reg = /^[a-z]$/; // 26个英文字母任何一个字母返回 true - 表示的是a 到z 的范围 console.log(reg.test('a')); console.log(reg.test('z')); console.log(reg.test(1)); console.log(reg.test('A')); // 字符组合 var reg1 = /^[a-zA-Z0-9_-]$/; // 26个英文字母(大写和小写都可以)任何一个字母返回 true console.log(reg1.test('a')); console.log(reg1.test('B')); console.log(reg1.test(8)); console.log(reg1.test('-')); console.log(reg1.test('_')); console.log(reg1.test('!')); console.log('----------------'); // 如果中括号里面有^ 表示取反的意思 千万和 我们边界符 ^ 别混淆 var reg2 = /^[^a-zA-Z0-9_-]$/; console.log(reg2.test('a')); console.log(reg2.test('B')); console.log(reg2.test(8)); console.log(reg2.test('-')); console.log(reg2.test('_')); console.log(reg2.test('!')); 7.3.3、量词符 量词符用来设定某个模式出现的次数 量词说明*重复零次或更多次+重复一次或更多次?重复零次或一次{n}重复n次{n,}重复n次或更多次{n,m}重复n到m次 // 量词符: 用来设定某个模式出现的次数 // 简单理解: 就是让下面的a这个字符重复多少次 // var reg = /^a$/; // * 相当于 >

= 0 can occur 0 or many times / / var reg = / ^ aplink; / / console.log (reg.test ('')); / / console.log (reg.test ('a')); / / console.log (reg.test ('aaaa')); / / + equals > = 1 can occur 1 or many times / / var reg = / ^ asides / / / console.log (reg.test ('')); / / false / / console.log (reg.test ('a')); / / true / / console.log (reg.test ('aaaa')); / / true / /? Is equivalent to 1 | | 0 / / var reg = / ^ aplink; / / console.log (reg.test ('')); / / true / / console.log (reg.test ('a')); / / true / / console.log (reg.test ('aaaa')); / / false / / {3} is to repeat 3 times / / var reg = / ^ a {3} $/ / / console.log (reg.test ('')); / / false / / console.log (reg.test ('a')); / / false / / console.log (reg.test ('aaaa')); / / false / / console.log (reg.test (' aaa')); / / true / / {3,} greater than or equal to 3 var reg = / ^ a {3,} $/ Console.log (reg.test ('')); / / false console.log (reg.test ('a')); / / false console.log (reg.test ('aaaa')); / / true console.log (reg.test (' aaa')); / / true / / {3pm 16} greater than or equal to 3 and less than or equal to 16 var reg = / ^ a {3pm 6} $/ Console.log (reg.test (')); / / false console.log (reg.test ('a')); / / false console.log (reg.test ('aaaa')); / / true console.log (reg.test (' aaa')); / / true console.log (reg.test ('aaaaaaa')); / / false 7.3.4, username authentication

Functional requirements:

If the user name is entered legally, the following message is: the user name is legal and the color is green

If the user name is entered illegally, the following message is: the user name does not conform to the specification and the color is green

Analysis:

The user name can only be composed of letters, numbers, underscores or dashes, and the length of the user name is 6-16 digits.

First of all, prepare this regular expression pattern / $[a-zA-Z0-9 mae _] {6pr 16} ^ /

Validation begins when the form loses focus.

If it conforms to the regular specification, add the right class to the following span tag.

If it does not conform to the regular specification, then add the wrong class to the following span tag.

Please enter the user name / / quantifier is to set the number of times a pattern occurs var reg = / ^ [a-zA-Z0-9 times -] {6jue 16} $/ / / users in this mode can only enter alphanumeric underscores, dashes, and [], which limits the choice of 1 / / {6pc16} without spaces / / console.log (reg.test ('a')); / / console.log (reg.test ('8')); / / console.log (reg.test ('18')) / / console.log (reg.test ('aa')); / / console.log (' -'); / / console.log (reg.test ('andy-red')); / / console.log (reg.test (' andy_red')); / / console.log (reg.test ('andy007')) / / console.log (reg.test ('andyroom007')); var uname = document.querySelector (' .uname'); var span = document.querySelector ('span'); uname.onblur = function () {if (reg.test (this.value)) {console.log (' correct'); span.className = 'right'' Span.className [XSS _ clean] = 'user name format is entered correctly';} else {console.log ('incorrect'); span.className = 'user name format input is incorrect';}} 7.4, parenthesis summary

The inner face of the braces quantifier indicates the number of repetitions.

The set of square brackets characters matches any character in the formula brackets

Parentheses indicate priority

/ / the square bracket character set matches any character in the formula braces var reg = / ^ [abc] $/; / / a | b | | var reg = / ^ abc {3} $/; / / it just makes c repeat 3 times. Abccc// parentheses indicate priority var reg = / ^ (abc) {3} $/; / / it makes abc repeat 3 times 7.5, predefined class.

Predefined classes refer to the shorthand of some common patterns.

The predetermined class description\ d matches any number between 0-9, which is equivalent to [0-9]\ D matching all characters other than 0-9, equivalent to [^ 0-9]\ w matching any letter, number and underscore, equivalent to [A-Za-z0-9]\ W characters except all letters, numbers, and underscores, and equivalent to [^ A-Za-z0-9]\ s matching spaces (including line breaks). Tabs, spaces, etc.), equivalent to [\ t\ t\ n\ v\ f]\ S matching non-space characters, equivalent to [^\ t\ r\ n\ v\ f] 7.5.1, form validation

Analysis:

1. Mobile number: / ^ 1 [3 | 4 | 5 | 7 | 8] [0-9] {9} $/

2.QQ: [1-9] [0-9] {4,} (Tencent QQ number starts from 10000)

3. The nickname is in Chinese: ^ [\ u4e00 -\ u9fa5] {2pr 8} $

/ / landline number verification: there are two formats of national landline numbers: 010-12345678 or 0530-1234567 / / or symbols in the rules | / / var reg = / ^\ d {3} -\ d {8} |\ d {4} -\ d {7} $/; var reg = / ^\ d {3} 4} -\ d {7} $/ 7.6. Substitution in regular expressions 7.6.1, replace substitution

The replace () method implements a replacement string operation, and the parameter to be replaced can be a string or a regular expression.

StringObject.replace (regexp/substr,replacement)

First parameter: replaced string or regular expression

Second parameter: the string to replace with

The return value is a new replaced string

/ / replace replacevar str = 'andy and red';var newStr = str.replace (' andy','baby'); var newStr = str.replace (/ andy/,'baby'); 7.6.2, regular expression parameters / expressions / [switch]

There are three patterns in which switch matches.

G: global match

I: ignore case

Gi: global match + ignore case

The above is about the content of this article on "how to open the strict mode of JavaScript". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report