匿名函数没有自己的this

更新日期: 2020-02-06阅读: 1.4k标签: 匿名函数

匿名函数没有自己的this,因此,在构造对象中调用全局函数时,可以省去保存临时this,再将其传入全局函数这一步: 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>匿名函数的this</title>
</head>
<body>
<script>
const Tom = {
name:'Tom',
age:null,
setAge: function () {
let _this = this; // 将Tom保存在_this变量里
setTimeout(function(){
// 因为是在全局函数里,所以这里的this是window
console.log(this); // 输出:window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
// 这里的_this才是Tom,所以用_this才能调用Tom的age属性
_this.age = 15;
console.log(_this) // 输出: {name: "Tom", age: 15, setAge: ƒ}
}, 1000);
}
};

Tom.setAge();
setTimeout(() => {
console.log(Tom.age);
}, 3000);

const Rose = {
name: 'Rose',
age: null,
setAge: function () {
setTimeout(() => { // 匿名函数没有this,因此匿名函数中的this是他所在函数的上一层,setTimeout()的上层是Rose
// 因此这里的this是Rose,可以调用Rose
this.age = 16;
console.log(this); // 输出:{name: "Rose", age: 16, setAge: ƒ}
}, 1000);
}
};

Rose.setAge();
setTimeout(() => {
console.log(Rose.age);
}, 3000);
</script>
</body>
</html>


 

链接: https://www.fly63.com/article/detial/8885

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!