gpt4 book ai didi

javascript - 构造函数中Object.defineProperty的获取中的"undefined"

转载 作者:行者123 更新时间:2023-11-28 13:04:07 24 4
gpt4 key购买 nike

我无法理解我在显示firstName 和lastName 方法的当前值的方式上犯了什么错误。现在,我在 jone.Name 和 jone.last 中遇到错误,因为它们得到 - 未定义。

function User(fullName) {
this.fullName = fullName.split(' ');

Object.defineProperty(this, 'firstName', {
get: function() {
this.firstName = this.fullName[0];
return this.firstName;
}
});

Object.defineProperty(this, 'lastName', {
get: function() {
this.lastName = this.fullName[1];
return this.lastName;
}
});

}

var jone= new User("Jone Coven");

console.log(jone.fullName);
console.log(jone.firstName);
console.log(jone.lastName);

最佳答案

问题在于 this.firstName = ...this.lastName = ... 覆盖已使用 Object.defineProperty 定义的属性(这个,...).

这是一个使用附加私有(private)属性 this._firstNamethis._lastName 的固定版本:

function User(fullName) {
this.fullName = fullName.split(' ');

Object.defineProperty(this, 'firstName', {
get: function() {
this._firstName = this.fullName[0]; // <------ _firstName
return this._firstName;
}
});

Object.defineProperty(this, 'lastName', {
get: function() {
this._lastName = this.fullName[1]; // <----- _lastName
return this._lastName;
}
});

}

var jone= new User("Jone Coven");

console.log(jone.fullName);
console.log(jone.firstName);
console.log(jone.lastName);
<小时/>

另一种解决方案是立即返回结果:

function User(fullName) {
this.fullName = fullName.split(' ');

Object.defineProperty(this, 'firstName', {
get: function() {
return this.fullName[0];
}
});

Object.defineProperty(this, 'lastName', {
get: function() {
return this.fullName[1];
}
});

}

var jone= new User("Jone Coven");

console.log(jone.fullName);
console.log(jone.firstName);
console.log(jone.lastName);
<小时/>

关于javascript - 构造函数中Object.defineProperty的获取中的"undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47940378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com