"未定义"在构造函数中获取Object.defineProperty

时间:2017-12-22 11:00:17

标签: javascript constructor get set

我无法理解我在显示firstName和lastName方法的当前值时出错了。现在我在jone.Name和jone.last中有一个错误,因为它们得到 - 未定义。

<el-table :data="myData" stripe="stripe">
  <el-row>
    <el-table-column prop="position" label="Col1">...</el-table-column>
    <el-table-column prop="position" label="Col2">...</el-table-column>
    <el-table-column prop="position" label="Col3">...</el-table-column>
  </el-row>
  <el-row>
    <el-table-column prop="position" label="Col4">...</el-table-column>
    <el-table-column prop="position" label="Col5">...</el-table-column>
    <el-table-column prop="position" label="Col6">...</el-table-column>
  </el-row>

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

为什么会这样复杂?

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

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

答案 2 :(得分: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());