ES5普通函数的this执行是: this指向运行时的函数调用者!
ES6的新特性箭头函数的this指向是:
"箭头函数中的this是在定义函数的时候绑定,而不是在执行函数的时候绑定。"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>This指向</title>
</head>
<body>
<script>
// 普通函数
let general = {
name: "天天向上",
fun: function () {
console.log("我是general下的fun" , this);
},
fun2: function (){
let obj = function () {
console.log("我是general下的fun2",this);
}
obj();
}
}
// 调用普通函数
general.fun();
general.fun2();
// 箭头函数
let arrows = {
name: "好好学习",
arr: () => {
console.log("我是arraws下的arr" , this);
},
arr2: function () {
let obj = () => {
console.log("我是arrows下的arr2里的obj",this);
}
obj();
}
}
// 调用箭头函数
arrows.arr()
arrows.arr2();
</script>
</body>
</html>
运行结果:
普通函数不管定义在哪里,永远是谁调用this指向谁!
箭头函数本身没有this,它的this引用外层的this比如:
arr()它是arrows对象的一个方法,arr()本身没有this,向上找arrows定义在全局里它的this是window所以arr()的this指向window.
arr2()里的obj函数,它定义在arr2()函数里,obj没有this,向上找找到arr2()它的this指向arrows,所以obj的this指向arrows.
推荐箭头函数用在与this无关的回调里,比如setTImeout,setInterval等,想事件回调最好还用普通回调!