箭头函数
1:语法
- ( )=> {…} // 零个参数用()表示
- x => {…} // 一个参数可省略()
- (x, y)=> {…} // 多参数不能省略()
- 函数体是多行语句时需要用{ }括起来,单行表达式不需要{ },并且会作为函数值返回
2:特性
箭头函数是匿名函数
- 箭头函数没有 自己的 arguments ;它的 arguments 来自于父级作用域;但可以用 … 解构运算符解决
var a = () => {
console.log("args:", arguments);
}
a(1,2,3) // Uncaught ReferenceError: arguments is not defined
function foo() {
setTimeout(() => {
console.log(arguments);
}, 1);
}
foo(1, 2, 3, 4) // [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
var a = (...value) => {
console.log("value:", value);
}
a(1,2,3) // value:[1,2,3]
- 箭头函数没有 prototype 属性,所以不支持 new 操作,不能用作构造函数
- 箭头函数中对于this的处理也与普通函数不同:箭头函数中的 this 始终等于它上层的上下文中的 this / 定义位置父级的上下文
- 箭头函数中的 this 即使使用 call, bind, apply也无法改变
var a = 1
b= {
a: 10,
test:() => this.a
}
}
b.test() // 1
b.test.call(b) // 依然是 1
继续做题:箭头函数中的 this(与JS关于this的指向笔记略有重合)
let obj1 = {
sayHi:function() {
setTimeout(function () {
console.log(this.a) // undefined
},100)
},
a: 'hello'
}
obj1.sayHi()
let obj2 = {
sayHi:function() {
setTimeout(() => {
console.log(this.a) // hello
},100)
},
a: 'hello'
}
obj2.sayHi()
// sayHi这个函数使用的也是箭头函数,它的this就也会向上层寻找,而它的再上层就是全局,故最终 this.a 指向 window,找不到变量a,返回undefined
let obj3 = {
sayHi:() => {
setTimeout(() => {
console.log(this.a) // undefined
},100)
},
a: 'hello'
}
obj3.sayHi()
var a=200;
let obj={
a:100,
fn:function(){ //es5 谁调用,this指向谁
console.log(this.a);
},
foo:()=>{ // es6箭头函数的this指向父级(obj)上下文。
console.log(this.a)
}
}
obj.fn();// 100;
obj.foo();//200