十七、箭头函数vs普通函数
-
this指向问题
-
箭头函数:this指向在定义时就决定的 ➡️ 不可修改(call、apply、bind)
- this指向:外层第一个普通函数的this(没有自己的this)
-
普通函数:使用时决定this指向 ➡️ 可通过call、apply、bind修改
- this指向:调用该函数的对象
let obj = { a: function(){ console.log(this) }, //this = obj b: () => { console.log(this) } //this = window }
let obj = { run: function(){ console.log(this) // obj return () => { console.log(this) } //obj }, speak: function(){ return function(){ console.log(this) } } } obj.run().call(window) //未更改为window, this = obj obj.run()() // this = obj obj.speak() // this = window
-
-
构造函数
-
箭头函数:不能当作构造函数new(也不可用super)
-
普通函数:可以new = 构造函数
let run = () => { return 111 } console.log(new run()) //报错
-
-
原型
-
箭头函数:没有prototype
-
普通函数:有prototype
let run = () => {} console.log(run.prototype) //undefined
-
-
参数
-
箭头函数:没有arguments ➡️ 用rest参数解决
let fn = (...args) => { console.log(args) } fn() //数组形式输出
-
普通函数:有arguments
let run = () => { console.log(arguments) } run() //报错:arguments没有定义 let walk = function(){ console.log(arguments) } walk() //Arguments[callee:f, Symbol(Symbol.iterator)]
-
-
Generator函数:
-
箭头函数:不能使用yeild关键字 ➡️ 不可以当作Generator函数
-
普通函数:可使用yield关键字 ➡️可用于Generator函数
箭头函数:this指向上下文、不可new、没有原型 ➡️ 匿名函数
-