简体   繁体   English

为什么 this.key 在 JavaScript 中不能正常工作?

[英]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();

I'm new to OOP in Javascript, I understand that the 3 ways in which I wrote a method work exactly the same.我是 Javascript 中 OOP 的新手,我知道我编写方法的 3 种方式完全相同。

student.sayHi(); works and shows up the alert => "Hi my name is Carlos"工作并显示警报 =>“嗨,我的名字是 Carlos”

but student.sayHiAgain();但是student.sayHiAgain(); shows up the alert => "Hi my name is undefined"显示警报 =>“嗨,我的名字未定义”

What am I missing?我错过了什么?

When using arrow functions, it uses lexical scoping meaning that it refers to it's current scope and no further past that, ie, binds to the inner-function and not to the object itself.当使用箭头函数时,它使用词法范围,这意味着它指的是它当前的 scope 而不是更远的过去,即绑定到内部函数而不是 object 本身。

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.箭头 function 表达式是常规 function 表达式的语法紧凑替代方案,尽管没有与 this、arguments、super. 或 new.target 关键字的绑定。 Arrow function expressions are ill suited as methods, and they cannot be used as constructors. Arrow function 表达式不适合用作方法,并且不能用作构造函数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Arrow functions have no “this” 箭头函数没有“this”

Arrow functions are special: they don't have their “own” this.箭头函数很特殊:它们没有“自己的” this。 If we reference this from such a function, it's taken from the outer “normal” function.如果我们从这样的 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();

Arrow function expressions 箭头 function 表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM