ES6已经出现很长时间了,现在系统一下知识点,查漏补缺。
变量
let
let
声明的变量只在其所在的代码块中起作用。
- 使用
let
声明变量之前。该变量是不可用的 - 暂时性死区
let
不允许在同一个作用域内重复声明同一个变量。
- 在块级作用域内函数声明类似于
let
,在块级作用域之外不可引用。
const
const
声明一个只读变量,一旦声明常量不可变。
const
实际上保证的是变量指向的那个内存地址不得改动,引用类内部属性还是可变的。
获取顶层对象
1 2 3 4 5 6
| function getGlobal(){ if ( typeof self !== 'undefined' ) { return self; } if ( typeof window !== 'undefined' ) { return window; } if ( typeof global !== 'undefined' ) { return global; } throw new Error("unable to locate global object !!! "); }
|
结构赋值 - 按照一定的模式从数组或者对象中提取值,然后对变量进行赋值。
字符串
Unicode(utf-8/utf-16)字符表示方法:\u{0061}
\u{20BB7}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| var buf = "𠮷a";
buf.codePointAt(0).toString(16); buf.codePointAt(1).toString(16);
String.fromCodePoint(0x20bb7);
for(let c of buf){ console.log(c); }
'abc'.at(0);
'x'.padStart(5, 'yz'); 'x'.padStart(4, 'yz');
'x'.padEnd(5, 'yz'); 'x'.padEnd(4, 'yz');
var template = `this is an template String ${buf}`;
function compile(template){ let evalExpr = /<%=(.+?)%>/g; let expr = /<%=([\\s\\S]+?)%>/g; template = template .replace(evalExpr, '`); \\n echo( $1 ); \n echo(`') .replace(expr, '`); \n $1 \\n echo(`'); template = 'echo(`'+ template +'`);'; var script = `(function parse(data){ let output = ""; function echo(html){ output += html; }
${ template }
return output; })`; return script; }
let parse = eval(compile(template)); let html = parse(data);
|
正则
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| new RegExp('xyz','i'); new RegExp(/xyz/i); /xyz/i; new RegExp(/xyz/ig,"i");
|
- 先行断言:x只有在y前面才能匹配
/x(?=y)/
- 先行否定断言: x只有不在y前面才能匹配
/x(?!y)/
- 后行断言:x只有在y后边才能匹配
/(?<=y)x/
- 后行否定断言:x只有不在y后面才能匹配
/(?<!y)x/
匹配Unicode \p{...}
或者 \P{...}
具名组匹配 ?<name>
1 2 3
| const RE_DATE = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const matchObj = RE_DATE.exec('1999-12-31'); const year = matchObj.groups.year;
|
数值
二进制前缀 0b
八进制前缀 0o
十六进制前缀 0x
Number
对象
1 2 3 4 5 6 7
| Number.isFinite() Number.isNaN() Number.parseInt() Number.parseFloat() Number.isInteger() Number.EPSILON Number.isSafeInteger()
|
Math
对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| Math.trunc() Math.sign() Math.cbrt() Math.clz32() Math.imul() Math.fround() Math.hypot()
Math.expm1() Math.log1p() Math.log10() Math.log2()
Math.sinh() Math.cosh() Math.tanh() Math.asinh() Math.acosh() Math.atanh()
Math.signbit()
|
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| function log(x,y='World'){ console.log(x,y); } function log({x = 'Hello',y = 'World'}={}){ console.log(x,y); } function log({x,y} = {x:'Hello',y:'World'}){ console.log(x,y); }
function throwMissing(param){ throw new Error("Missing parameter " + param ); } function log(x = throwMissing('x'),y='World'){ console.log(x,y); }
function log(x, ...y){}
let sum = (x, y) => x + y ;
function f(x){ return g(x); }
function tco(f){ var value; var active = false; var accumulated = [];
return function accumulator(){ accumulated.push(arguments)l if(!active){ active = true; while(accumulated.length){ value = f.apply(this, accumulated.shift()); } active = false; return value; } }; }
var sum = tco(function(x,y){ if(y>0){ return sum(x + 1,y - 1); }else{ return x; } });
sum(1,100000);
function abc(a,b,c,){
}
|
数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
arr = [1] arr2 = [2,3] arr3 = [4,5] [...arr, ...arr2, ...arr3] [first, ...rest] = [1,2,3,4,5] Array.from() Array.of() arr.copyWithin() arr.find() arr.findIndex() arr.fill() arr.entries() arr.keys() arr.values() arr.includes()
|
对象
1 2 3 4 5 6 7 8
| Object.is() Object.assign(target, ...sources) function clone(origin){ let originProto = Object.getPrototypeOf(origin); return Object.assign(Object.create(originProto),origin); } Object.getOwnPropertyDescriptor();
|
对象遍历
- for...in 遍历自身和继承的可枚举属性(不含Symbol属性)
- Object.keys(obj) 遍历自身(不含继承)的可枚举属性(不含Symbol属性)
- Object.getOwnPropertyNames(obj) 遍历自身的所有属性(不含Symbol属性)
- Object.getOwnPropertySymbols(obj) 遍历自身所有Symbol属性
- Reflect.ownKeys(obj) 遍历自身所有属性
1 2 3 4 5 6 7 8 9 10 11 12
| Object.setPrototypeOf(object, prototype) Object.getPrototypeOf() Object.keys(object) Object.values(object) Object.entries(object) Object.getOwnPropertyDescriptor(object, 'propName') Object.getOwnPropertyDescriptors(object)
var a = b?.c?.d?.e;
|
Symbol 独一无二的值
七种数据类型:Undefined
、Null
、 Boolean
、 String
、 Number
、 Object
、 Symbol
使用方式:
1 2 3 4 5
| let s = Symbol();
let s = Symbol('abc');
|
Symbol
作为属性名,可以用于构建枚举量或者内部方法。
1 2
| Symbol.for() Symbol.keyFor()
|
对象的11个内置Symbol
值
- Symbol.hasInstance
- Symbol.isConcatSpreadable
- Symbol.species
- Symbol.match
- Symbol.replace
- Symbol.search
- Symbol.split
- Symbol.iterator
- Symbol.toPrimitive
- Symbol.toStringTag
- Symbol.unscopables
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class MyClass{ [Symbol.hasInstance] (p) { return p instanceof Array; } } [1, 2, 3] instanceof new MyClass();
let obj = {length:2, 0:'c', 1:'d'}; ['a','b'].concat(obj,'e');
obj[Symbol.isConcatSpreadable] = true; ['a','b'].concat(obj,'e');
|
Set Map
- Set - add delete has clear size
- WeakSet - 成员只能是对象
- Map - size set get has delete clear
- WeakMap - 仅接受对象作为键名 没有size属性
- WeakMap 很适合实现listener 和 部署私有属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| function strMapToObj(strMap){ let obj = Object.create(null); for(let [k,v] of strMap){ obj[k] = v; } return obj; }
function objToStrMap(obj){ let strMap = new Map(); for(let k of Object.keys(objs)){ strMap.set(k,obj[k]); } return strMap; }
function strMapToJson(strMap){ return JSON.stringify(strMapToObj(strMap)); } function mapToArrayJson(strMap){ return JSON.stringify([...strMap]); }
function jsonToStrMap(jsonStr){ return objToStrMap(JSON.parse(jsonStr)); } function jsonToMap(sonStr){ return new Map(JSON.parse(jsonStr)); }
|
Proxy 修改某些操作的默认行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| get() set() apply() has() construct() deleteProperty() defineProperty() getOwnPropertyDescriptor() getPrototypeOf() isExtensible() ownKeys() preventExtensions() setPrototypeOf() Proxy.revocable()
|
Reflect 类似 Proxy
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Reflect.apply Reflect.construct Reflect.get Reflect.set Reflect.defineProperty Reflect.deleteProperty Reflect.has Reflect.ownKeys Reflect.isExtensible Reflect.preventExtensions Reflect.getOwnPropertyDescriptor Reflect.getPrototypeOf Reflect.setPrototypeOf
|
Promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| var promise = new Promise(function(resolve,reject){
if(){ resolve(value); }else{ reject(error); } }); promise.then(function(value){ },function(error){ }).catch(console.error);
function timeout(ms){ return new Promise((resolve,reject) => { setTimeout(resolve, ms, 'done'); }); } timeout(100).then((value) => console.log(value));
function loadImageAsync(url){ return new Promise((res,rej)=>{ let image = new Image(); image.onload = function(){ res(image); }; image.onerror = function(){ rej(new Error("Could not load image at " + url)); }; image.src = url ; }); }
function getJSon(url){ return new Promise((res, rej)=>{ let client = new XMLHttpRequest(); client.open("GET",url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); function handler(){ if(this.readyState !== 4){ return ; } if(this.status === 200){ res(this.response); }else{ rej(new Error(this.statusText)); } } }); }
var a = Promise.all([new Promise(),new Peomise()]);
var a = Promise.race([new Promise(),new Peomise()]);
Promise.prototype.done = function(onFulfilled, onRejected){ this.then(onFulfilled, onRejected).catch(function(reason){ setTimeout(function(){throw reason;},0); }); }
Promise.prototype.finally = function(callback){ let P = this.constructor; return this.then( value => P.resolve(callback()).then(() => value), reason => P.resolve(callback()).then(() => { throw reason}) ); }
|
Iterator 和 for ... of
Genertor函数 异步编程解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| function* gen(){ yield "hello"; yield "world"; yield "ending"; } var g = gen(); g.next(); g.next();
function* clock(){ while(true){ console.log("tick!"); yield; console.log("tock!"); yield; } }
var Thunk = function(fn){ return function(){ var args = Array.prototype.slice.call(arguments); return function (callback){ args.push(callback); return fn.apply(this, args); }; }; };
const Thunk = function(fn){ return function(...args){ return function(callback){ return fn.call(this, ...args,callback); }; }; };
|
async 改进 gen函数
1 2 3 4 5 6
| async function funcName(){ var f1 = await readFile(); } funName();
|
Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Point{ constructor(x,y){ this.x = x; this.y = y; this.__a = 123; console.log('point run'); } set prop(str){ console.log(str); } get prop(){ return "123"; } toString (){ return "hello"; } static say(){ console.log(this.__a); } } Point.prop = 1;
class ColorPoint extends Point{ constructor(){ super(1,1); console.log('color point run'); } }
|
修饰器
Module语法
1 2 3 4 5
| import {stat, exist, readFile} from 'fs'; var a = 1; var b = 2; export const A = 1; export {a as c, b};
|