1、使用到了setTimeout函数,困惑:为什么使用() => {}。
setTimeout(() => {
if (XXX)
{ this.save();
}
this.index = null;}, 10);
2、查看setTimeout()的定义:
declare function setTimeout(handler: TimerHandler, timeout?: number, ...arguments: any[]): number;
第一个参数是TimerHandler,查看其格式定义
type TimerHandler = string | Function;
发现该参数需要是string或者function。
3、() => {}是js中匿名函数的定义方式
(a,b) => {console.log(a);}
相当于
function(a,b){console.log(a);}
同理
setTimeout(() => {
if (XXX)
{ this.save();
}
this.index = null;}, 10);
可以写成
setTimeout(
function() {
if (XXX)
{ this.save(); }
this.index = null;
}, 10);
但尝试写成上面的方式却报错了,原因在于:
箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。
this的指向:使用function定义的函数,this的指向随着调用环境的变化而变化,而箭头函数中的this指向是固定不变的,一直指向定义函数的环境。
//使用function定义的函数
function foo(){
console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }
//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window