箭头函数
箭头函数的特点
- this指向的问题 对于普通的函数 谁调用 就会指向谁 但是对于箭头函数 其this的指向是定义箭头函数的上下文 代码示例-1
var name = 'jsck';
let obj = {
age: 12,
name: 'mary',
sayHi: function() {
console.log(this.name);
}
}
let obj_a = {
age: 12,
name: 'mary',
sayHi: () => {
console.log(this.name);
}
}
obj.sayHi(); // mary
obj_a.sayHi(); // jsck
如上面的代码 虽然obj_a去调用了 sayHi 这个函数 但是由于是一个箭头函数 我是直接在全局状态下写的 所以 this的指向就是 window
代码示例-2
var name = 'jack'
function King() {
this.name = 'mary';
setTimeout(() => {console.log(this.name)}, 2000)
}
function Queen() {
this.name = 'mary';
setTimeout(function(){
console.log(this.name);
}, 2000)
}
let k = new King(); // mary
let q = new Queen(); // jack
- 箭头函数没有自己的 prototype 也就是没有原型 注意 它是有constructor的 从而会导致 它没有办法作为构造函数 也不能使用new
-箭头函数没有argument 但是可以通过扩展运算符的方式去获取参数
let f = (...values) => {
console.log(values);
}
f(1, 2, 3) // [1, 2, 3];