// ES5普通函数
var sum = function(x, y) {
return x + y
}
// ES6箭头函数
let sum = (x, y) => x + y // 再简洁
() => { ... } // 零个参数用 () 表示。
x => { ... } // 一个参数可以省略 ()。
(x, y) => { ... } // 多参数不能省略 ()。
如果只有一个return,{}可以省略。
// 普通函数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)
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]
let Person = (name) => {
this.name = name
};
let one = new Person("galler")
const full = ({ first, last }) => first + ' ' + last
// 等同于
function full(person) {
return person.first + ' ' + person.last
}
full({first: 1, last: 5}) // '1 5'
function A() {
this.foo = 1
}
A.prototype.bar = () => console.log(this.foo)
let a = new A()
a.bar() //undefined
var func = ()
=> 1 // SyntaxError: expected expression, got '=>'
// 此时需加{}和return
使用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)