需要在引擎盖下进行解释。在javaScript中的获取和设置
给出下面的代码,即使参数的名称位于开头的firstName,在使用setter设置它并查看对象的属性后,它变成了_firstName。我有 Java 开发背景,这对我来说似乎不合逻辑。有人可以解释一下吗?
class Person {
constructor(firstName, DOB, sport) {
this.firstName = firstName;
this.DOB = DOB;
this.sport = sport;
}
get firstName() {
return this._firstName;
}
set firstName(firstName) {
this._firstName = firstName;
}
}
const person1 = new Person('Marko', '2002', 'tennis');`
person1.firstName = 'Luka';
之后的对象
(Person {_firstName: 'Luka', DOB: '1256', _sport: 'tennis'}
DOB: "1256"
_firstName: "Luka"
_sport: "tennis"
DO: undefined
firstName: (...)
sport: (...)
[[Prototype]]: Object)
我尝试了 person1.firstName = 'Luka';
并期望对象字段保持firstName,但它变成了_firstName(带下划线) 。我看到我在这一行 this._firstName = firstName;
中进行了此更改,但我不明白如何覆盖变量名称
Given the code below even though the name of the parameter is on the beginning firstName, after setting it with setter and looking at the properties of an object it becomes _firstName. I am coming from a Java development background and this seems unlogical to me. Can somebody explain, please?
class Person {
constructor(firstName, DOB, sport) {
this.firstName = firstName;
this.DOB = DOB;
this.sport = sport;
}
get firstName() {
return this._firstName;
}
set firstName(firstName) {
this._firstName = firstName;
}
}
const person1 = new Person('Marko', '2002', 'tennis');`
Object after person1.firstName = 'Luka';
(Person {_firstName: 'Luka', DOB: '1256', _sport: 'tennis'}
DOB: "1256"
_firstName: "Luka"
_sport: "tennis"
DO: undefined
firstName: (...)
sport: (...)
[[Prototype]]: Object)
I tried person1.firstName = 'Luka';
and was expecting object field to stay firstName but it became _firstName (with underline). I see that I am making this change in this line this._firstName = firstName;
but I do not understand how can variable name be overriden
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this.firstName
是设置属性this._firstName
的方法。调用 setter 方法
this.firstName = "Marko"
的工作方式与调用this.firstName("Marko")
等标准方法类似。由于您在构造函数中使用该方法,因此当您实际使用方法this.firstName
时,“看起来”您正在设置属性this.firstName
来设置属性this._firstName
。修改
this.firstName
方法有助于理解这一点:您应该在控制台上看到 setter 方法被使用过一次。现在尝试将构造函数的第一行更改为
this._firstName = firstName;
this.firstName
is a method setting the propertythis._firstName
.Calling the setter method
this.firstName = "Marko"
works similar to calling a standard method likethis.firstName("Marko")
. Since you're using the method in your constructor it "looks like" you're setting the propertythis.firstName
when you're actually using the methodthis.firstName
to set the propertythis._firstName
.Modifying
this.firstName
method helps understand this:You should see on the console that the setter method was used once. Now try changing the first line of your constructor to
this._firstName = firstName;