Speaking of JavaScript, everyone knows that it is A scripting language. So what the hell is ES? ES stands for ECMAScript, which is the international standard for JavaScript language.
Recently summarized some knowledge points related to the basic features of js, let’s take a look at it together
1. Strict mode
Using strict mode, you can perform stricter global and local error condition checks inside the function
Strict mode pragma, "use strict"
Create global variables, undeclared variables , in non-strict mode, create a global variable; in strict mode, throw ReferenceError
Call the delete operator on the variable to delete the variable, in non-strict mode, it will fail silently; in strict mode, throw ReferenceError
In the case of operating objects: a, read-only attribute assignment will throw TypeError; b, using the delete operator on non-configurable attributes will throw TypeError; c, adding attributes to non-extensible objects will throw TypeError.
Duplicate-named attributes: a. There is no error in non-strict mode, and the second attribute shall prevail; b. A syntax error will be thrown in strict mode.
Function parameters must be unique. If there are parameters with the same name, there will be no error in non-strict mode. Only the second parameter can be accessed; in strict mode, an error will be thrown.
There can only be one method named "constructor" in a class. If the constructor method appears multiple times, a SyntaxError will be thrown
In a constructor method, it can Use super to call the constructor of a parent class
If a constructor method is not specified, a default constructor will be used
3. Class attribute Setter and Getter
var daObj = { get val() { return ; }, set val(value) { } }复制代码
get:
var da = { a: 1, get val(){ return this.a + 1; } }console.log(da.val);//2da.val = 100;console.log(da.val);//2class Da { constructor(type) { this.type = type } get age() { return 1 } set age(val) { this.realAge = val } eat() { console.log('i am eat') } }let da1 = new Da('da1')console.log(da1.age) da1.age = 1console.log(da1.realAge)复制代码
class Da { constructor(type, age) { this.type = type this.age1 = age } get age() { return this._age } set age(val) { this._age = val } }复制代码
Use set/get to encapsulate element.innerHTML
class myHTMLElement { constructor(element) { this.element = element } get html() { return this.element.innerHTML } set html(value) { this.element.innerHTML = value } }复制代码
Set a closure and use certain rules to Limit modifications to it:
let myName = 'dada' class Da { constructor(type) { this.type = type } get name() { return myName } set name(val) { myName = val } }复制代码
4. Static method
Static method implemented in es5:
let Da = function (type) { this.type = type this.eat = function() { console.log('i eat') } } Da.study = function(book) { console.log('i book'); }复制代码
let Da = function(type) { this.type = type } Da.prototype.eat = function() { Da.walk() console.log('i am') } Da.walk = function(){ console.log('walk') }let da1 = new Da('da1') da1.eat()// walk// i am复制代码
The static method cannot be found in your instantiated object The
static method in es6, marked static
class Da { constructor(type) { this.type = type } eat() { console.log('i eat') } static study() { console.log('i study') } }复制代码
class Da { constructor(type) { this.type = type } eat() { // Da.walk(); console.log('i eat') } static walk(){ console.log('i walk') } }class da extends Da { // 构造函数 //constructor (type) { //super(type) //} run() { console.log('i run') } }let da1 = new da('da1')复制代码
6. Object-oriented programming Class
Class declaration, properties, methods, static methods, inheritance, polymorphism, private properties
// 类的声明 let Da = function(type) { this.type = type this.eat = function() { console.log('i eat'); } } let da = new Da('da');复制代码
// prototype let Da = function(type) { this.type = type } Da.prototype.eat = function() { console.log('i eat') } let da1 = new Da('da1')复制代码
Class
class Da { // 构造函数 constructor(type) { this.type = type } // 方法 walk() { console.log('i walk') } } let da = new Da('da'); // console.log(typeof Da); function复制代码
7 in es6. Default value of function parameters
Function parameters are parsed from left to right. If there is no default value, it will be parsed intoundefined
// 参数默认值 function da (x,y,z) { } function sum() { let num = 0 Array.prototype.forEach.call(arguments, function(item){ num += item * 1 }) Array.from(arguments).forEach(function(item){ num += item * 1 }) return num }复制代码
// 不确定 function sum(...nums) { let num = 0 nums.forEach(function(item){ num += item * 1 }) return num } console.log(sum(1,2,3,4,5))复制代码
function sum () { let num = 0 Array.prototype.forEach.call(arguments, function (item) { num += item * 1 }) return num } function sum (...nums) { let num = 0 nums.forEach(function (item) { num += item * 1 }) return num }复制代码
8.es6 Arrow function
Arrow function expressions have a more concise syntax than function expressions and do not have their own this, arguments, super or new. target. Arrow function expressions are more suitable where an anonymous function would otherwise be required, and it cannot be used as a constructor.
() => {} // function Da() {} // let da = function() {} let da = () => { console.log('hello') } da() let da = name => {}复制代码
The property definition of the object in JS, the code example is as follows:
let x = 'da1'; let y = 'da2'; let obj = { x, y } console.log(obj); // 结果 {x:'da1',y:'da2'}复制代码
let x=1; let y=2; let z=3 let obj = { 'x': x, y, [z+y]: 4, * hello() { // 异步 console.log('dada') } } // function* functionName() {} obj.hello()复制代码
11.Set data structure
The members stored in Set are not allowed to be repeated (it is similar to an array)
Set itself is a constructor used to generate the Set data structure.
const s = new Set(); [2, 3, 5].forEach(x => s.add(x)); Set 函数可以接受一个数组(或类似数组的对象)作为参数,用来初始化 const set = new Set([1, 2, 3, 4, 4]);复制代码
Implementing array deduplication
var arr = [1,1,2,2,3,3]; // step1:数组转集合 var s = new Set(arr); // 已经去掉重复值,当前不是数组,而集合 s.size; // 3 // step2:集合转数组 console.log([...s]); // 1,2,3; // Array.form 方法可以将 Set 结构转为数组 const items = new Set([1, 2, 3]); const arr = Array.from(items); function dada(array) { return Array.from(new Set(array)); } dada([1, 1, 2])复制代码
Set traversal
keys():返回键名的遍历器
values():返回键值的遍历器
entries():返回键值对的遍历器
forEach():使用回调函数遍历每个成员
操作方法
add(value):添加某个值,返回Set结构本身。
delete(value):删除某个值,返回一个布尔值,表示删除是否成功。
has(value):返回一个布尔值,表示该值是否为Set的成员。
clear():清除所有成员,没有返回值。
let set = new Set([1, 2, 3, 4, 4]); // 添加数据 let addSet = set.add(5); console.log(addSet); // Set(5) {1, 2, 3, 4, 5} // 删除数据 let delSet = set.delete(4); console.log(delSet); // true // 查看是否存在数据 4 let hasSet = set.has(4); console.log(hasSet); // false // 清除所有数据 set.clear(); console.log(set); // Set(0) {}复制代码
实现并集(Union)、交集(Intersect)和差集(Difference)
let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2, 1]); // 并集 let union = new Set([...a, ...b]); // Set {1, 2, 3, 4} // 交集 let intersect = new Set([...a].filter(x => b.has(x))); // set {1, 2, 3} // 差集 let difference = new Set([...b].filter(x => !a.has(x))); // Set {4}复制代码
12.Map数据结构
JS当中的哈希表,使用方法如下:
let map = new Map() map.set(1, 2) map.set(3, 4) map.set(1, 3) console.log(map) 创建 var da = new Map(); var jeskson = {}; 遍历 da.forEach(function(value,key,map){} 长度 da.size 删除 //da.delete() 删除key,全部清楚da.clear() 新增 da.set(key,value) da.has(查索引值) da.forEach((value,key) =>{ }) for( let [key, value] of map){} // let map = new Map( [[1,2], [3,4]] ) map的key任意都可以 let o = function() { console.log('o') } map.set(o, 3) console.log(map.get(o)); // 3复制代码
var myArray = ['a', 'b', 'c'];var one = myArray[0], two = myArray[1], three = myArray[2];// one = 'a', two = 'b', three = 'c'复制代码
ES6解构允许使用更简单方法:
const [one, , three] = myArray;// one = 'a', three = 'c'复制代码
使用rest运算符(...)提取剩余元素:
const [one, ...two] = myArray;// one = 'a', two = ['b, 'c']复制代码
const myObject = { one: 'a', two: 'b', three: 'c'};// ES6 destructuring exampleconst {one: first, two: second, three: third} = myObject;// first = 'a', second = 'b', third = 'c'复制代码
可变值交换
var a = 1, b = 2;// ES5 swapvar temp = a; a = b; b = temp;// a = 2, b = 1// ES6 swap back[a, b] = [b, a];// a = 1, b = 2[b, c, d, e, a] = [a, b, c, d, e];复制代码
在ES6中,我们可以为任何参数分配默认值
function dada(param = {}) {复制代码
函数返回多个值(函数只能返回一个值,但可以是一个复杂的对象或多维数组)
function f() { return [1, 2, 3]; }const [a, b, c] = f();// a = 1, b = 2, c = 3复制代码
ES6 JavaScript深度解构
默认情况下,找不到的属性为undefined
var {da} = {bar: 'dada'}console.log(da)// undefined复制代码
如果访问不存在的父级的深层嵌套属性,则将获得异常。
var {da:{bar}} = {dada: 'dadaqianduan'}// Exception复制代码
var person = { name: "dada", age: 17}; person = new Proxy(person, { set(target, property, value) { if (value === 18) { console.log("Congratulations! You are of legal age"); Reflect.set(target, property, value); return true; } } }); person.age = 18;if (value < 13 && value > 99) { throw new Error('The age should be between 13 and 99') } else { Reflect.set(target, property, value) }复制代码
语法:
let p = new Proxy(target, handler)复制代码
target 用Proxy包装的目标对象
handler 一个对象,其属性是当执行一个操作时定义代理的行为的函数
如果不想再调用key的时候,返回undefined:
console.log(o.dada || '')复制代码
使用Proxy
let o = { name: 'dada', age: 1}let handler = { get(obj, key) { return Reflect.has(obj, key)?obj[key]:'' } }let p = new Proxy(o, handler)console.log(p.from)复制代码
希望从服务器获取的数据只读,不允许修改:
for (let [key] of Object.entries(response.data)) { Object.defineProperty(response.data, key, { writable: false }) }复制代码
使用Proxy:
let data = new Proxy(response.data, { set(obj, key, value) { return false } })复制代码
检验逻辑代码:
// Validator.jsexport default(obj, key, vlaue) => { if(Reflect.has(key) && value > 20) { obj[key] = value } }import Validator from './Validator'let data = new Proxy(response.data, { set: Validator })复制代码
使用Proxy,对读写进行监控:
let validator = { set(target, key, value) { if(key === 'age') { if(typeof value !== 'number' || Number.isNaN(value)) { throw new TypeError('Age must be a number') } if(value<=0){ throw new TypeError('Age must be a positive number') } } return true } }const person = { age: 12 }const proxy = new Proxy(person,validator) proxy.age = 'dada' // TypeError numberproxy.age = NaNproxy.age = 0 // positive numberproxy.age = 3复制代码
示例:每个对象都有一个自己的id
class Component { constructor() { this.proxy = new Proxy({ id: Math.random().toString(36).slice(-8) }) } get id() { return this.proxy.id } }复制代码
18.Generator
function * dada() { for(let i=0; i<2; i++ { yield console.log(i); } } const da = dada() da.next() da.next()复制代码
Generator函数与普通函数的区别在于定义的时候有一个*,执行下面函数:
function* dada() { console.log('dadaqianduan'); } dada(); // 没有执行函数 如需要输出,改为: var da = dada(); da.next();复制代码
要生成一个自增的id:
var count_id = 0; function dada_id() { count_id ++; return count_id; }复制代码
导出变量或者常量 export const da = 'dadaqianduan' export let da1 = 'da1' export var da2 = 'da1' const name = 'dada' let name1 = 'dada1' export { name, name1 } 导出函数 export function da(value){ console.log(value) } const da = (value) => { console.log(value); } export { da } 导出Object export({ name: 'da1', message: 'dadaqianduan' }) let da = { name: 'name1' } export { da } 导出Class class Da { constructor(){ this.id = 1 } } export { Da } export class Da { constructor() { this.id = 1 } } 修改导出名称 const name = 'da1' export { name as cname } export default name复制代码
import
// 直接导入 const name = 'dada' let name1 = 'dada1' var name2 = 'dada2' export { name as cname } export default name2 import name2, {name1, name} from A复制代码
export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function dada(x,y) { return sqrt(square(x) + square(y)); } import {square,da} from 'da'; console.log(square(11)); // 121 console.log();复制代码
export default function() {...} import myFunc from 'myFunc'; export default class{...} import MyClass from 'MyClass'; const inst = new MyClass();复制代码
20.import, export
require --lib.js-- function add(x,y){ return x + y } module.exports = { add: add, }; --main.js-- var add = require('lib').addd; console.log(add(1,2));复制代码
import --lib.js-- export function add(x,y) { return x + y } --main.js-- import {add} from 'lib'; console.log(add(1,2));复制代码
--lib.js-- export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function da(x,y) { return sqrt(square(x)+square(y)); } --main.js-- import {square, da} from 'lib' --myFunc.js-- export default function() {...}; --main.js-- import myFunc from 'myFunc'; myFunc();复制代码
21.Array.prototype.includes,Promise
该方法判断一个数组是否包含一个指定的值,返回布尔值
let da1 = [1,2,3]; console.log(da1.includes(2));复制代码
function da(time) { return new Promise(function(resolve,reject){ setTimeout(function(){ resolve(time) },time) }) } async function test() { let arr = [da(2000),da(1000),da(3000)] for await (let item of arr) { console.log(Date.now(), item) } }复制代码
The above is the detailed content of After fighting with wolfberry for many nights, I summarized 25 important knowledge points about JavaScript and ES.. For more information, please follow other related articles on the PHP Chinese website!
Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete