匿名函数没有自己的this
匿名函数没有自己的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>
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!