在构造函数中获取Object.defineProperty中的“undefined”

问题描述 投票:0回答:3

我无法理解我在显示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);
javascript constructor get set
3个回答
3
投票

问题是this.firstName = ...this.lastName = ...覆盖了已经使用Object.defineProperty(this, ...)定义的属性。

这是一个使用其他私有属性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);


2
投票

为什么这会复杂化?

function User(fullName) {
  this.fullName = fullName.split(' ');
  this.firstName = this.fullName[0];
  this.lastName = this.fullName[1];
}

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

0
投票
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());
© www.soinside.com 2019 - 2024. All rights reserved.