跳至主要內容

模板字符串与箭头函数

Mr.Chen前端进阶ES6模板字符串箭头函数大约 3 分钟约 1016 字

模板字符串

什么是模板字符串?

;`alex`

模板字符串和一般字符串的区别

const person = {
  username: 'alex',
  sex: 'male',
  age: 18,
}
//  一般字符串
//  const info='我的名字是:'+person.username+',性别:'+person.sex+',今年'+person.age+'岁了'
// 模板字符串
const info = `我的名字是:${person.username},性别:${person.sex},今年${person.age}岁了`
console.log(info)

和其他东西一起使用的时候,使用模板字符串,方便注入。

模板字符串的注意事项

  1. 输出多行字符串
// 一般字符串
const info = '第一行\n第二行'
console.log(info)
// 模板字符串
const info = `第一行
           第二行`
console.log(info)

模板字符串中,所有的空格,换行或缩进都会被保留正在输出之中。(怎么写就怎么输出)

  1. 输出`和\等特殊字符

使用转义字符

const info = `\\`
console.log(info)
const info = `\``
console.log(info)
  1. 模板字符串的注入

${} 只要最终能得到一个值的就能放在花括号里面!

const username = 'alex'
const person = { age: 17, sex: 'male' }
const getSex = function (sex) {
  return sex === 'male' ? '男' : '女'
}
const info = `${username},${person.age + 2},${getSex(person.sex)}`
console.log(info)

模板字符串的应用

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>学生信息表</title>
  </head>
  <body>
    <p>学生信息表</p>
    <ul id="list">
      <li style="list-style-type:none;">信息加载中……</li>
    </ul>

    <script>
      // 数据
      const students = [
        {
          username: 'Alex',
          age: 18,
          sex: 'male',
        },
        {
          username: 'ZhangSan',
          age: 28,
          sex: 'male',
        },
        {
          username: 'LiSi',
          age: 20,
          sex: 'female',
        },
      ]
      const list = document.getElementById('list')
      let html = ''
      for (let i = 0; i < students.length; i++) {
        html += `<li>我的名字是:${students[i].username},${students[i].sex},${students[i].age}</li>`
      }
      //  延迟两秒加载数据
      setTimeout(function () {
        list.innerHTML = html
      }, 2000)
    </script>
  </body>
</html>

箭头函数

箭头函数是什么?

  • 认识箭头函数
const add = (x, y) => {
  return x + y
}
  • 箭头函数的结构

const/let 函数名 = 参数 => 函数体

箭头函数的注意事项

  • 单个参数可以省略圆括号
const add = x => {
  return x + 1
}
  • 无参数或多个参数不能省略圆括号
const add()=>{
    return 1+1
}
  • 单行函数体可以同时省略{}和 return ,多行函数体不能再化简了
const add = (x, y) => x + y
  • 如果箭头函数返回单行对象,可以在{}外面加上(),让浏览器不再认为那是函数体的花括号。
// 完整写法
// const add=(x,y)=>{
//   return {
//     value:x+y
//   }
// }
// const add=(x,y)=>{value:x+y} js会把{}认为是函数的花括号而不是对象的,所以会报错!
const add = (x, y) => ({ value: x + y })

箭头函数中的 this 指向

箭头函数没有自己的 this,而是根据外层作用域来决定 this

eg1:

const calc = {
  add: () => {
    console.log(this) //作用链查找,对象没有作用域,找到全局作用域中的this,指向window
  },
}
calc.add()

eg2:

const calc ={
    add:function (){
        const adder=()=>{
            console.log(this) // calc
        }
    }
    adder()
}
calc.add()
const addFn=calc.add
addFn() // undefined->window

不适用箭头函数的场景

  • 作为构造函数:因为箭头函数没有 this

  • 需要 this 指向调用对象的时候:如事件处理函数

  • 需要使用 arguments 的时候

箭头函数的应用

我们需要 setInterval 中的 this 指向 timer。es6 之前使用普通函数,setInterval 中的 this 指向 window,可以采用备份上下文的方法:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>箭头函数的应用</title>
  </head>
  <body>
    <button id="btn">开始</button>
    <span id="result">0</span>

    <script>
      var btn = document.getElementById('btn')
      var result = document.getElementById('result')
      var timer = {
        time: 0,
        start: function () {
          var that = this
          btn.addEventListener(
            'click',
            function () {
              setInterval(function () {
                that.time++
                result.innerHTML = that.time
              }, 1000)
            },
            false
          )
        },
      }

      timer.start()
    </script>
  </body>
</html>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>箭头函数的应用</title>
  </head>
  <body>
    <button id="btn">开始</button>
    <span id="result">0</span>

    <script>
      const btn = document.getElementById('btn')
      const result = document.getElementById('result')
      const timer = {
        time: 0,
        start: function () {
          //this
          btn.addEventListener(
            'click',
            () => {
              setInterval(() => {
                this.time++
                result.innerHTML = this.time
              }, 1000)
            },
            false
          )
        },
      }

      timer.start()
    </script>
  </body>
</html>
上次编辑于: