在构造函数中获取Object.defineProperty中的“undefined”
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在构造函数中获取Object.defineProperty中的“undefined”相关的知识,希望对你有一定的参考价值。
我无法理解我在显示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());
以上是关于在构造函数中获取Object.defineProperty中的“undefined”的主要内容,如果未能解决你的问题,请参考以下文章
可以在构造函数中获取值,但是在render函数中输出TypeError: Cannot read property 'xxx' of undefined