[英]Why isn't this.key working properly in JavaScript?
let student = { fname: "Carlos", lname: 'Dubón', sayHi(){ alert(`Hi my name is ${this.fname}`); }, sayBye: function() { alert(`Bye ${this.fname}`); }, sayHiAgain: ()=> { alert(`Hi my name is ${this.fname}`); } } student.sayHiAgain();
我是 Javascript 中 OOP 的新手,我知道我編寫方法的 3 種方式完全相同。
student.sayHi();
工作並顯示警報 =>“嗨,我的名字是 Carlos”
但是student.sayHiAgain();
顯示警報 =>“嗨,我的名字未定義”
我錯過了什么?
當使用箭頭函數時,它使用詞法范圍,這意味着它指的是它當前的 scope 而不是更遠的過去,即綁定到內部函數而不是 object 本身。
箭頭 function 表達式是常規 function 表達式的語法緊湊替代方案,盡管沒有與 this、arguments、super. 或 new.target 關鍵字的綁定。 Arrow function 表達式不適合用作方法,並且不能用作構造函數。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
箭頭函數很特殊:它們沒有“自己的” this。 如果我們從這樣的 function 中引用它,它取自外部“正常”function。
let student = { fname: "Carlos", lname: "Dubón", sayHi: function () { console.log(`Hi my name is ${this.fname}`); }, sayBye: function () { console.log(`Bye ${this.fname}`); }, sayHiAgain: function () { console.log(`Hi my name is ${this.fname}`); }, }; student.sayHiAgain();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.