当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 匿名函数没有自己的this

匿名函数没有自己的this

2020年05月06日  | 移动技术网IT编程  | 我要评论

匿名函数没有自己的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>

 

 

 

输出:

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网