- 标准函数
function myFunc(){
}
- 箭头函数
let myFunc = () => {
}
箭头函数需要注意,函数体如果使用{},需要加return才能返回
let a = value => value+1;
let b = value => {value + 1};
console.log(a(1));
console.log(b(1));
- 区别
两者this引用的对象不同。
在标准函数中,this引用的是把函数当成方法调用的上下文对象。粗浅的说,在标准函数中,谁调用该函数,则该行函数的this指向谁。
在箭头函数中,this引用的是定义箭头函数的上下文。
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
</head>
<body>
<script>
window.color = 'red';
function func1() {
console.log(this, this.color);
}
let func2 = ()=>{
console.log(this, this.color);
}
let obj = {
color: 'green'
}
obj.func1 = func1;
obj.func2 = func2;
obj.func1();
obj.func2();
</script>
</body>
</html>
- 修改this的指向
bind、call、apply都可以修改标准函数的this的指向,但是箭头函数的this继承自定义时的上下文,所以无法修改。