我无法理解我在显示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._firstName
和 this._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/