ES6 模板字符串、箭头函数、扩展运算符

(一)、模板字符串

ES5中声明字符串可以用 [“string”] [’ string’],单、双引号进行声明
ES6中引入反引号

我们可以在反引号中直接使用换行符

`There are items
   in your basket, 
  are on sale!`

模板字符串还可以嵌入变量,格式是 ${ } 大括号中放入变量

var num = 3
var str = `这里有${num}个苹果`

${ } 大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"

模板字符串之中还能调用函数。

function fn() {
  return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar

(二)、箭头函数

1 . 没有自己的this,this始终指向函数声明时,所在作用域下的this的值

var name = "zhangsan"
var obj = {
    name:"lisi",
    callName:()=>{
        console.log(this.name)
    }
}
obj.callName()
// name   zhangsan

2 . 不能作为构造函数

var cons = ()=>{
    name:"zhangsan";
    age:24;
}
var person = new cons();
//  cons is not a constructor

3 . 不能使用 arguments 变量及rest参数的使用

let foo = ()=>{
    console.log(arguments)
}

foo("foo")
// arguments is not defined

箭头函数虽然不被允许使用arguments,但是允许使用rest参数,且一般function声明的函数也可以使用rest参数

function foo() {
    console.log(arguments)
}
foo(1, 2, 3, 4, 5)
// 输出 arguments 对象,本质是对象
function foo(...rest) {
    console.log(rest)
}
foo(1, 2, 3, 4, 5)
// 输出 rest 参数数组,本质是数组,可以调用各种数组api

rest参数必须放在最后

function foo(a, b, ...rest) {
    console.log(a, b, rest)
}
foo(1, 2, 3, 4, 5)
//  1 2 (3) [3, 4, 5]

4 . 箭头函数的简写
如果只有一个形参时,可以省略小括号

let foo = n =>{
    console.log(n)
}
foo(5)

如果代码体只有一条,可以省略大括号和 return 关键字

let foo = n => console.log(n)
foo(5)

箭头函数很经典的一个应用场景

<div id="box" style="width: 100px;height: 100px;background-color: blue;"></div>

var box = document.getElementById("box");
        box.addEventListener("click", function () {
            setTimeout(function () {
                console.log(this)
                this.style.backgroundColor = "pink"
            }, 1000)
        })
        // 报错,this的指向为Window

// 解决方案,将外层的this进行值保存,此时外层的this还指向调用该函数的DOM元素
var box = document.getElementById("box");
        box.addEventListener("click", function () {
            let _this = this;
            setTimeout(function () {
                console.log(this)
                _this.style.backgroundColor = "pink"
            }, 1000)
        })

// 解决方案,使用箭头函数,因为箭头函数没有自己的this,它的this就是调用该事件的DOM元素
var box = document.getElementById("box");
        box.addEventListener("click", function () {
            setTimeout(() => {
                this.style.backgroundColor = "pink"
            }, 1000)
        })

箭头函数适合与this无关的回调,如定时器,数组回调的函数
箭头函数不适合作为与this有关的回调,比如DOM2级的事件回调

扩展运算符

扩展运算符可以把数组,扩展成参数序列

var arr = [1,2,3,4,5]
console.log(...arr)
// 1 1 2 3 4 5

应用1,数组合并

var arr1 = [1, 2, 3]
var arr2 = [5, 6, 7]
var arr3 = [...arr1, ...arr2]
console.log(arr3)
// (6) [1, 2, 3, 5, 6, 7]

应用2,数组克隆

var arr1 = [1, 2, 3]
var arr2 = [...arr1]
console.log(arr2)
// (3) [1, 2, 3]

应用3,可以把伪数组变成真正的数组,这样伪数组就可以使用所有数组的方法了

猜你喜欢

转载自blog.csdn.net/qq_40893035/article/details/108263213