es678910 syntactic sugar

Playfully:
new es js progress, and progress is programmed, es6 five years have passed, and compatible with the rate of 90%, or 10% of the mobile phone is not compatible, that in the end should or should not take care of those who can not keep up people, I think it should not happen, new es can write five lines of function, why I use the old write 50 lines, but also so difficult to understand, difficult to maintain, but I still compatible, people under the eaves, not not bow

== Label == es is backward compatible with the tools mentioned in this node classification, do not say here

All content from the blog Ruan Yifeng power of God
at 12:00 on November 9th, 2019, the contents of the blog foreword from 0 to 31 [link] reference
often used api have

  • and let const
  • Deconstruction and expand assignment operator
  • Expand string
  • Digital expansion
  • Function expansion and expansion operators
  • And expand the array Iterator
  • Expand the object
  • The new type Set and Iterator
  • New Map and type Iterator
  • Reflect
  • Proxy observer
  • Promise
  • async
  • class
  • module

and let const

  • var let instead, let no variable lift, can be understood as js code parsing process, let encountered will automatically skipped during execution to identify
  • const is not variable, but is fixed lit, if the underlying data type can not be modified the first assignment value if the data type is, can modify the contents inside, but can not modify the data type, and a scope is only a function can be declared once, that is, can not be declared twice aa, will complain, can protect this value is not easily be changed or re-declared another programmer
    a write == some details on the next ==

Assignment deconstruction
deconstruction assignment into arrays and objects deconstruction deconstruction

Deconstruction array is according to the order, and the left with deconstruction array, it must be the right array

// 基础应用
// 可以理解为右边的数组是ajax请求来的res
let [a, b, c] = [1, 2, 3];
console.log(a,b,c)

// 跳过使用
let [ , , c] = ["foo", "bar", "baz"];
console.log(c)  // "baz"

// 二级数组
let [a, b, d] = [1, [2, 3], 4];
console.log(b)  //[2,3]

// 拓展运算符
// 拓展运算符一次赋值只能用一次,而且只能用在最后一位
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

Object deconstruction
objects deconstruction key is assigned, there is no order of
objects than deconstruct array with much, much deconstruction

// 基础应用
// 可以理解为右边的数组是ajax请求来的res
let { bar,foo,ceshi} = { foo: 'aaa', bar: 'bbb' };
console.log(bar,foo,ceshi)  // 'bbb','aaa',undefined

// 上面的写法其实是对象的省略写法,因为key-value同名所以缩写
// 如果不缩写是 let { bar:bar,foo:foo,ceshi:ceshi} = { foo: 'aaa', bar: 'bbb' };
// 所以不缩写可以重命名
let { bar:newBar,foo:newFoo,ceshi:newCeshi} = { foo: 'aaa', bar: 'bbb' };
console.log(newBar,newFoo,newCeshi)  // 'bbb','aaa',undefined

// 默认值
var {x = 1} = {};
console.log(x) //1

// 上面的默认值也是省略写法
var {x:newX = 1} = {x: 5};
console.log(newX) //5

//清除对象里不要的key
let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}

Strings expand
on their understanding of the code

var basket = {
   count: 10,
   onSale: "aa"
}
// 原先的字符串拼接
$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);

// 新版的字符串拼接,两端是``斜点
// 数据是${...},
// 可以用默认值 ${ name || "pdt" }
// 可以用简单的方法${ time2date(time) }
$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

Digital expansion
prior to digital string is reduced to zero by

Number("123")

// 转不了的就是NaN
Number("123a")  //NaN

Expanding the function
has a default value of the parameter, the parameter deconstruction, expansion parameter operator, arrow function

// 参数默认值
// 以往的参数默认值是这样的
function init(name){
   var name = name || "pdt"
}

// es6可以
function init(name = "pdt"){ ... }
// 参数解构
// 老版本
function init(arr,obj){ ... }
init([1,2],{name:"pdt",age:18})

// 新写法
function init([,b],{name="无名"}){
   //比如我只需要数组的第二个和name属性
   console.log(a,b,name)
}
init([1,2],{name:"pdt",age:18})

//参数必填
const required = () => {throw new Error('Missing parameter')};
const add = (a = required(), b = required()) => a + b;
add(1, 2) //3
// 箭头函数,是function的缩写
// 但是不能作为对象的value,不能作为数组的值,不能作为构造函数
// 箭头函数没有自己的this
// 箭头函数没有三个改变this的方法
// 箭头函数没有arguments

// 声明
var init = () => { ... }

// 作为参数
function init(cb){
   cb(111)
}
// 旧版
init(function(num){ console.log(num )})
// 箭头函数
init((num)=>{ console.log(num })

== arrow retain this function is used, specifically to see the next ==

Expanding array of
new es to increase the array to a call Iteratorthings, this view "traverse summary"
added a lot of ways to traverse this view "traverse summary"
There expanding operator instead apply the method function (apply What to see "context and scope")

// ES5取数组的最大值
Math.max.apply(null, [14, 3, 77])
// ES6取数组的最大值
Math.max(...[14, 3, 77])

// ES5合并数组
arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6合并数组
[...arr1, ...arr2, ...arr3]

// ES5把伪数组转成数组
Array.prototype.slice.apply(null,ArrayLike)
// ES6把伪数组转成数组
[...ArrayLike]
// 或者新api
Array.from(ArrayLike)

// ES5查看是否含有,返回第一个出现的位置,没有是-1
arr.indexOf("xx")
// ES6查看是否含有,返回true/false
arr.include("xx")

Extended objects

// 最后一个key-value可以加逗号了
var obj = {
   name: "name",
   age: 18,  //以前这里结束加逗号是不行的
}

// key-value同名可以省略
// 比如要ajax传个参数
var name = "name",age = 18;
ajax({
   // 以前
   // data:{ name: name, age:  gae }
   // 现在可以
   data:{name,age}
})

// 对象的value是function的写法优化
// 老写法
var obj = {
   say: function(){ ... }
}
// 新写法
var obj = {
   say(){ ... }
}

// 对象的遍历,查看《遍历的总结》
// 增加可Obj.vaules() 和 Object.entries()

// 对象的合并assign,这个api是浅拷贝
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}
// 也可以
let target = {...target, ...source1}

The new type Set [collection]
Set with an array of almost the same object is a deformity
he will automatically go heavy, but only to re-base data type

// 需要通过new去创建,参数是一个数组或者伪数组
let set = new Set([undefined,undefined,NaN,NaN,"",""]); //  set{"undefined",NaN,""}

// set的长度属性
set.size  //3

// 添加某个值,返回set本身,所以可以无限add()
set.add(value)
// 删除某个值,返回一个布尔值,表示删除是否成功
set.delete(value)
// 返回一个布尔值,表示该值是否为Set的成员
set.has(value)
// 清除所有成员,没有返回值
set.clear()

// Set没有办法取值,只能转数组再取值
[...set]
// 或者
Array.from(set)

// Set的遍历,set.keys(),set.values(),set.entries()
// 具体查看《遍历总结》

// 还有一个WeakSet,不重要
// 他跟Set一样,只是他只能存对象,并且带有垃圾回收功能,面试题来着
const ws = new WeakSet();

Several features of the collection

let a = new Set([1, 2, 3]);
let b = new Set([4, 3, 2]);

// 并集
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

// 交集
let intersect = new Set([...a].filter(x => b.has(x)));//ES6
var intersect = new Set([...a].filter(function(x){
    return b.has(x);
}))
// set {2, 3}

// 差集
let difference = new Set([...a].filter(x => !b.has(x)));
// Set {1}

The new type Map [Dictionary]
Map structure provides a corresponding value-value compared to the Object, his key can be any type

// 通过new创建,参数是一个数组,数组里的值必须都是两个长度的数组
const map = new Map([
  ['name', '张三'],
  ['title', 'Author']
]);

// map的长度属性
map.size // 2


// 添加某个值,返回set本身,所以可以无限add()
map.set(key, value)
// 返回一个布尔值,表示该值是否为Set的成员
set.has(key)
// 
map.get(key) 
// 删除某个值,返回一个布尔值,表示删除是否成功
map.delete(key)
// 清除所有成员,没有返回值
map.clear()

// Map的遍历,map.keys(),map.values(),map.entries()
// 具体查看《遍历总结》

// Map转数组,其实map挺好用的,没必要转,除非是要传给后端
[...map]


// 还有一个WeakMap,不重要
// 只接受对象作为键名(null除外),不接受其他类型的值作为键名
const wm = new WeakMap();

== In fact, Set and Map are also very rare, because the arrays and objects have been well spent, but also to be compatible, but also to turn the format and turn ==

Reflect
Reflect is ES6 objects in order to operate the new API, with the proxy data operation is simply perfect

Reflect.get(target, name, receiver)
Reflect.set(target,name,value,receiver)
Reflect.apply(target,thisArg,args)
Reflect.construct(target,args[, newTarget])
Reflect.defineProperty(target,name,desc)
Reflect.deleteProperty(target,name)
Reflect.has(target,name)
Reflect.ownKeys(target)
Reflect.preventExtensions(target)
Reflect.isExtensible(target)
Reflect.getOwnPropertyDescriptor(target, name)
Reflect.getPrototypeOf(target)
Reflect.setPrototypeOf(target, prototype)

Proxy observer
this is generally less than, and belong to the architecture level api, Vue3.0 is to use this as infrastructure, like Object.defineProperty, this place "vue design principles," said

// 贴个基础代码
var obj = new Proxy({}, {
  get: function (target, key, receiver) {
    console.log(`getting ${key}!`);
    return Reflect.get(target, key, receiver);
  },
  set: function (target, key, value, receiver) {
    console.log(`setting ${key}!`);
    return Reflect.set(target, key, value, receiver);
  }
});

Promise
View "promise article"
Promise should be filled with asynchronous function, if it is synchronized but is produces BUG

// 贴个基础代码
new Promise(function(resolve, reject) {
  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
}).then((value)=>{ ... },(error)=>{ ... })

Async
View "promise article"
follow behind await promise is asynchronous function, if it is synchronized but is produces BUG

// 贴个基础代码
async function main() {
  try {
    const val1 = await firstStep();
    const val2 = await secondStep(val1);
    const val3 = await thirdStep(val1, val2);
    console.log('Final: ', val3);
  }
  catch (err) {
    console.error(err);
  }
}

class
view "class" chapter
class is a new type constructor

// 贴个基础代码
class A {
  constructor(name) {
     // 静态属性/方法
    this.name = name;
  }
  // 相当于原型方法,class不支持原型属性
  print() {
    console.log(this.name);
  }
  // 带有static是私有方法/属性,通过A.myMethod()执行
  static myMethod() {
    console.log('static');
  }
}

class B extends A {
  constructor(name,age) {
    //继承的
    super();
    this.name = name;
    this.age= age;
  }
  m() {
    console.log(this.age);
  }
}

let b = new B("pdt",18);
b.m() // 18
b.print() // "pdt"

module
view "modular" chapter
introducing new api js file but is not supported, the browser did not support even nodejs support

// 开放多个,只能全是export,不能有export default
// fs.js
export function A(){ ... }
export B = { ... }
export C = []
export D = "D"

// 引入并且解构赋值
import { A, B, C, D } from 'fs';
// 只能出现一个export default,并且不能有其他export
// default就不需要名字了
// fs.js
export default function(){ ... }
// 或者对象,其他格式都行
export default {}

// 引入并且解构赋值
import fs from 'fs';

In addition to the above common
as well as Symbol, Decorator decorator []

Decorator article

  1. Method Decorator function decorator
  2. Property Decorators familiar decorator
  3. Class Decorator class decorator
  4. Parameter Parameter Decorator decorator
    future decorator will become the new framework, it will be manufactured as Springframes

Say a few
of these api js upgrade of difficulty to produce a lot of play and framework, so that he is no longer a front-end jq trying to conquer the chicken dish, more and more things he needs to learn, these high imitation from a lot of api language, especially java
example expanding operator, Iterator walker, Set, Map, await native is a yeild, this is, as well as class, model of the import java, Decorator is annotated java and NodeJs of stream flow, etc. Wait

Guess you like

Origin www.cnblogs.com/pengdt/p/12037960.html