function sum(x, y){
return x + y
}
let sum = function(x, y){
return x + y
}
console.log(4, 5)
第一种方式会存在一个函数的预定义,如果在上面调用的,会先预定好,不管是先调用还是后调用都不会报错 第二种存在变量提升的问题,在调用的时候,sum 并没有赋值,不存在变量提升的情况下就会提示未定义
ES6 中箭头函数的写法会简单很多
let sum = (x, y) => {
return x + y
}
console.log(sum(3, 4))
箭头函数的左边是参数,右边是函数的函数体
如果只有一行代码,可以直接简写 let sum = (x, y) => x + y
箭头函数跟普通函数的差别
// <button id='btn'>click me</button>
let oBtn = document.querySelectAll('#btn')
oBtn.addEventListener('click', function(){
// console.log(this)
// setTimeout(function(){
// console.log(this) // this 指向了window
// }.bind(this), 1000)
setTimeout(()=>{
console.log(this) // <button id='btn'>click me</button>
})
})
setTimeout是window里面的一个方法,所有this指向的window,可以通过.bind(this),
// 类
function People(name, age){
this.name = name
this.age = age
}
let p1 = new People('xx', 4)
console.log(p1)
let People = (name, age) => {
this.name = name
this.age = age
}
let p1 = new People('xx', 4)
console.log(p1) // People is not a constructor
箭头函数不可以当作构造函数去使用
let foo = function(){
console.log(arguments)
}
foo(1, 2, 3)
let foo = (...args) => {
// console.log(arguments) // arguments is not a defined
console.log(args) // [1, 2, 3]
}
foo(1, 2, 3)
箭头函数不可以使用 arguments,可以使用args 去代替 arguments 的作用