匿名函式沒有自己的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>
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/98456.html
標籤:JavaScript
上一篇:JavaScript閉包
下一篇:JavaScript入門
