ES6的小知识
1:函数的默认参数
1 function foo(x = 20, y = 30) { 2 console.log(x, y); 3 } 4 foo(50) 5 foo(undefined, '') //解决了之前的弊端 6 //默认值和解构结合 7 function bar({ name, age } = { name: 'tyy', age: 20 }) { 8 console.log(name, age); 9 } 10 11 function bar2({ m = 'tyy', n = 20 } = { m, n }) { 12 console.log(m, n); 13 } 14 bar() 15 bar2()

2:函数的剩余参数 ...args 和arguments不同的是arguments是所有的参数
1 function foo(m, n, ...args) { 2 console.log(m, n, args); 3 } 4 foo(1, 2, 3, 4, 5, 6, 7)

3:函数箭头函数
箭头函数上面没有prototype,所以不能作为构造函数使用new来创造对象
1 var foo = () => { 2 console.log(this); 3 } 4 console.log(foo.prototype); 5 var f = new foo()

4:展开语法
1 var names = ['tyy', 'tsf', 'zjj'] 2 var name = 'hei' 3 var obj = { mood: 'happy', age: 20 } 4 //1函数调用时 5 function foo(x, y, z) { 6 console.log(x, y, z); 7 } 8 foo(...names) 9 foo(...name) 10 //构造数组时 11 const newArr = [...name, ...names] 12 console.log(newArr); 13 //创建字面量对象时 会自动给数组添加索引 14 var newobj = {...obj, address: '广州市', ...names } 15 console.log(newobj);

特别注意的是展开运算符是一个浅拷贝
1 var obj = { mood: 'happy', age: 20, friends: { name: 'lili', age: 20 } } 2 var newobj = {...obj, address: '广州市'} 3 console.log(obj); 4 newobj.friends.name = 'happing' 5 console.log(newobj); 6 console.log(obj);

我们可以看到代码中只是把newobj里面的friends的name改变了,但是obj里面也改变了,这其实是一个浅拷贝,原理如下

5:Symbol的使用---用来生成一个独一无二的值
1 const s1 = Symbol() 2 const s2 = Symbol() 3 const s3 = Symbol() 4 const s4 = Symbol() 5 const s5 = Symbol() 6 const obj = {} 7 //写法一属性名赋值 8 obj[s1] = 'abc' 9 obj[s2] = 'cba' 10 console.log(obj); 11 //写法二 12 Object.defineProperty(obj, s3, { 13 value: 'qwe', 14 enumerable: true 15 }) 16 //写法三 定义字面量直接使用 17 const info = { 18 [s4]: 'iop', 19 [s5]: 'wer' 20 } 21 console.log(obj); 22 console.log(Object.getOwnPropertySymbols(info)); 23 const Symbolkeys = Object.getOwnPropertySymbols(info) 24 for (const key of Symbolkeys) { 25 console.log(info[key]); 26 }


浙公网安备 33010602011771号