我无法理解我在显示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(this, ...)
定义的属性。
这是一个使用其他私有属性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);
为什么这会复杂化?
function User(fullName) {
this.fullName = fullName.split(' ');
this.firstName = this.fullName[0];
this.lastName = this.fullName[1];
}
var jone= new User("Jone Coven");
function User(fullName) {
this.fullName = fullName.split(' ');
this.firstName = function() {
return this.fullName[0];
}
this.lastName = function() {
return this.fullName[1];
}
}
var jone= new User("Jone Coven");
console.log(jone.fullName);
console.log(jone.firstName());
console.log(jone.lastName());