匿名函数没有自己的this
匿名函数没有自己的this,因此,在构造对象中调用全局函数时,可以省去保存临时this,再将其传入全局函数这一步:
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>匿名函数的this</title>
7 </head>
8 <body>
9 <script>
10 const Tom = {
11 name:'Tom',
12 age:null,
13 setAge: function () {
14 let _this = this; // 将Tom保存在_this变量里
15 setTimeout(function(){
16 // 因为是在全局函数里,所以这里的this是window
17 console.log(this); // 输出:window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
18 // 这里的_this才是Tom,所以用_this才能调用Tom的age属性
19 _this.age = 15;
20 console.log(_this) // 输出: {name: "Tom", age: 15, setAge: ƒ}
21 }, 1000);
22 }
23 };
24
25 Tom.setAge();
26 setTimeout(() => {
27 console.log(Tom.age);
28 }, 3000);
29
30 const Rose = {
31 name: 'Rose',
32 age: null,
33 setAge: function () {
34 setTimeout(() => { // 匿名函数没有this,因此匿名函数中的this是他所在函数的上一层,setTimeout()的上层是Rose
35 // 因此这里的this是Rose,可以调用Rose
36 this.age = 16;
37 console.log(this); // 输出:{name: "Rose", age: 16, setAge: ƒ}
38 }, 1000);
39 }
40 };
41
42 Rose.setAge();
43 setTimeout(() => {
44 console.log(Rose.age);
45 }, 3000);
46 </script>
47 </body>
48 </html>
输出:

赞 (0)
