跳至主要內容

模板字符串与箭头函数

zfh大约 2 分钟约 649 字...

模板字符串

`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)

箭头函数

const add = (x, y) => {
  return x + y
}

注意事项

  • 单个参数可以省略圆括号
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(call,apply,bind)

和普通函数的区别

  1. 箭头函数没有自己的this
  2. call、apply、bind不会改变箭头函数的this指向
  3. 箭头函数不能作为构造函数使用
  4. 箭头函数没有arguments
  5. 箭头函数没有prototype
  6. 箭头函数不能用作Generator函数,不能使用yeild关键字
上次编辑于:
本站勉强运行 小时
本站总访问量
網站計數器