ES6 箭头函数和运算符(

27 阅读3分钟
  1. 异步的处理函数

  2. 事件的处理

  3. 继续去沿用外层的this

  4. 对象的属性不要去用箭头函数,除非是特别的需求

  5. 数组方法的时候,保证代码的简洁

回到顶部 目录

this的指向


ES5以前的this的指的是函数的调用对象,而ES6的箭头函数的this指向函数被调用时是上下文

const btn = document.getElementsByTagName('button')[0];

// 传统模式会报错因为当时的this指向window

btn.onclick = function(){

setInterval(function(){

console.log(this)//window

this.style.backgroundColor = rgb(${(Math.random() * 255) | 0},${(Math.random() * 255) | 0},${(Math.random() * 255) | 0});

}.bind(this),1000);

}

// 箭头函数的this指向是不会更改的

btn.onclick = function(){

setInterval(() =>{

console.log(this)//btn

this.style.backgroundColor = rgb(${(Math.random() * 255) | 0},${(Math.random() * 255) | 0},${(Math.random() * 255) | 0});

},1000);

}

语法:去掉function在()和{}之间加上=>:var a = (...参数) => {}

回到顶部 目录

参数默认值


// 传统模式

function fn1(num){

var num = num || 200;

return num;

}

// fn1这样有一个弊端当num = 0时,返回值为200

// 解决方法

function fn2(num){

var num = num === undefined ? 200 : num;

return num;

}

// ES6完美解决

function fn3(num = 200){

return num;

}

语法:直接在参数后面赋值:function(num = 2){}

  • 方法被调用时,如果没有给参数赋值,就为默认值

  • 方法被调用时,如果有给参数赋值,就为新赋值的值

回到顶部 目录

name 属性


function foo() {}

foo.name // "foo"

(new Function).name // "anonymous"

(function(){}).bind({}).name // "bound "

回到顶部 目录

rest参数


rest运算符的格式为:(…变量名)

rest在英文中意思代表剩余的意思

function fn (fister, second, ...arg){

console.log(arg.length);

}

fn(1,2,3,4,5,6,7,8) // 6

由代码可得出,rest参数就是代表剩余参数的集合

参数的书写方式(建议)

  1. 确定的参数

  2. 默认值参数

  3. rest参数

回到顶部 目录

扩展运算符(…)


扩展运算符的格式为:(…)

它就好比rest参数的逆运算(rest参数是将多个值存放到一个参数变量里面,而扩展运算符是将一个数组展开)

const a = [1,2,3,4,5];

// 扩展运算符的格式为:(...)

const b = [...a];

console.log(b) // [1,2,3,4,5]

console.log(b == a) // false

console.log(b === a) // false

  • 扩展运算符:和arguments差不多,但是arguments是类数组,并且arguments在严格模式中就没有效果了(所以以后就用…代替arguments)

  • 扩展运算符后面还可以放置表达式 ...(x > 0 ? ['a'] : [])

  • 扩展运算符后面是一个空数组,则不产生任何效果[...[], 1] 就等于 [1]

  • 只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错

扩展运算符带来的用途

function fn(a, b, c){}

let args = [0,1,2];

fn.apply(null, args); // ES5

fn(...args); // ES6

// 求数组最小值

Math.min.apply(null, [21, 3, 4]); // ES5

Math.min(...[21, 3, 4]); // ES6

// push函数

let arr1 = [1,2,3];

let arr2 = [4,5,6];

Array.prototype.push.apply(arr1,arr2); // ES5

arr1.push(...arr2); // ES6

const a1 = [1,2,3];

const a2 = a1; // 浅克隆改变a2的值,a1也会改变

const a3 = a1.concat(); // ES5

const a4 = [...a1]; // ES6

  • 合并数组

  • 与解构赋值结合

  • 字符串:将字符串转换为真正的数组[...'aaaa']

回到顶部 目录

尾调用


是指某个函数的最后一步是调用另一个函数(通过return关键字调用方法)。

function f (x){

return g(x);

}

上面代码中,函数f的最后一步是调用函数g,这就叫尾调用。

尾调用不一定出现在函数尾部,只要是最后一步操作即可。

以下三种情况,都不属于尾调用

// 情况一

function f(x){

let y = g(x);

return y;

}

// 情况二

function f(x){

return g(x) + 1;

}

// 情况三

function f(x){

g(x);

} 回到顶部 目录