Skip to content

Latest commit

 

History

History
198 lines (147 loc) · 4.17 KB

05. 箭头函数.md

File metadata and controls

198 lines (147 loc) · 4.17 KB

箭头函数

img

1. 箭头函数语法

// ES5普通函数
var sum = function(x, y) {
    return x + y
}

// ES6箭头函数
let sum = (x, y) => x + y // 再简洁
() => { ... } // 零个参数用 () 表示。

x => { ... } // 一个参数可以省略 ()。

(x, y) => { ... } // 多参数不能省略 ()。

如果只有一个return,{}可以省略。


2. 箭头函数中的 this

  • 箭头函数内的this值继承自外围作用域。
  • 运行时它会首先到它的父作用域找,如果父作用域还是箭头函数,那么接着向上找,直到找到我们要的this指向。
// 普通函数this
var name = 'leo'
var teacher = {
    name: "大彬哥",
    showName: function () {
        function showTest() {
            alert(this.name);
        }
        showTest()
    }
};
teacher.showName()
//结果是 leo,而我们期待的是大彬哥,这里this指向了window,我们期待指向teacher
// 箭头函数this
let name = 'leo'
let teacher = {
    name: "大彬哥",
    showName: function () {
        let showTest = () => alert(this.name);
        showTest()
    }
};
teacher.showName() // 大彬哥

由于this在箭头函数中已经按照词法作用域绑定了,所以,用call或者apply调用箭头函数时,无法对this进行绑定,即传入的第一个参数被忽略,这个设计节省了开发者思考上下文绑定的时间

var obj = {
    birth: 1996,
    getAge: function (year) {
        var b = this.birth // 1996
        var fn = y => y - this.birth // this.birth仍是1996
        return fn.call({birth:1990}, year)
    }
};
obj.getAge(2018) // 22 ( 2018 - 1996)

img


3. 箭头函数的特性

3.1 箭头函数没有 arguments
function foo() {
  return () => console.log(arguments)
}

foo(1, 2)(3, 4)  // 1,2 来自父作用域

箭头函数不绑定arguments,取而代之用rest参数…解决

var foo = (...args) => {
  return args
}

console.log(foo(1,3,56,36,634,6))    // [1, 3, 56, 36, 634, 6]
3.2 箭头函数中不能使用 new (即不能作为构造函数)
let Person = (name) => {
    this.name = name
};
let one = new Person("galler")
3.3 箭头函数可以与变量解构结合使用
const full = ({ first, last }) => first + ' ' + last

// 等同于
function full(person) {
  return person.first + ' ' + person.last
}

 full({first: 1, last: 5}) // '1 5'
3.4 箭头函数没有原型属性,且原型上使用箭头函数无效
function A() {
  this.foo = 1
}

A.prototype.bar = () => console.log(this.foo)

let a = new A()
a.bar()  //undefined
3.5 箭头函数不能换行
var func = ()
           => 1 // SyntaxError: expected expression, got '=>'
// 此时需加{}和return

4. 箭头函数使用场景

this指向明确

使用jQuery来展示一个每秒都会更新的时钟:

$('.time').each(function () {
  setInterval(function () {
    $(this).text(Date.now())
  }, 1000)
})
// 当尝试在setInterval的回调中使用this来引用DOM元素时,
// 很不幸,我们得到的只是一个属于回调函数自身上下文的this。

一个通常的解决办法是定义一个that或者self变量:

$('.time').each(function () {
  var self = this
  setInterval(function () {
    $(self).text(Date.now())
  }, 1000)
})

当使用箭头函数时,这个问题就不复存在了,因为它不产生属于它自己上下文的this:

$('.time').each(function () {
  setInterval(() => $(this).text(Date.now()), 1000)
})
简化回调函数
// 正常函数写法
[1,2,3].map(function (x) {
  return x * x
})

// 箭头函数写法
[1,2,3].map(x => x * x)