this.fullName = fullName&的构造函数逻辑split()方法

时间:2017-12-22 12:34:44

标签: javascript constructor get set

有人可以解释一下:

我们有两个相似的代码。它们的功能是相同的。但是在第一个代码中我们有一个正常的结果,在下一个代码中 - 非常奇怪。

我不明白为什么结果不同,因为我们只改变了分裂的值的变量 - 从var split中的声明 变量在第一种情况下变为直接在下一个中改变当前的this.fullName prop 。并在下面的相应代码中使用它们。

this.fullName = fullName;
var split = this.fullName.split(' ');

改变

this.fullName = fullName.split(' ');

我们的结果如此不同。

function User(fullName) {
  this.fullName = fullName;
  var split = this.fullName.split(' ');

  Object.defineProperty(this, 'firstName', {
    get: function() {
        return this.firstName = split[0];
    },

    set: function(newFisrtName) {
        this.fullName = newFisrtName + ' ' + split[1];
    }
  });

  Object.defineProperty(this, 'lastName', {
    get: function() {
        return this.lastName = split[1];
    },

    set: function(newLastName) {
        this.fullName = split[0] + ' ' + newLastName;
    }   
  });

}

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

delete jone.lastName; 

jone.lastName = 'Mashow';

console.log(jone.fullName); // Jone Mashow
console.log(jone.firstName); // Jone
console.log(jone.lastName); // Coven

-------上面代码的第二个变量--------

function User(fullName) {
  this.fullName = fullName.split(' ');


  Object.defineProperty(this, 'firstName', {
    get: function() {
        return this.firstName = this.fullName[0];
    },

    set: function(newFisrtName) {
        this.fullName = newFisrtName + ' ' + this.fullName[1];
    }
  });

  Object.defineProperty(this, 'lastName', {
    get: function() {
        return this.lastName = this.fullName[1];
    },

    set: function(newLastName) {
        this.fullName = this.fullName[0] + ' ' + newLastName;
    }   
  });

}

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

delete jone.lastName; 

jone.lastName = 'Mashow';

console.log(jone.fullName); // Jone Mashow
console.log(jone.firstName); // J
console.log(jone.lastName); // empty

2 个答案:

答案 0 :(得分:1)

第二个声明中的问题在于此方法

 set: function(newLastName) {
    this.fullName = this.fullName[0] + ' ' + newLastName; // here is the problem
} 

如果您查看此行,您会看到将 this.fullName 从数组转换为字符串

所以如果你试试这个

this.fullName[0] // you get J 
this.fullName[1] // you get O 

因为 this.fullName 现在是一个字符串而不是一个数组,这就是为什么第一个声明有效,因为您使用另一个变量拆分并且您没有更改它并且仍然存在阵列。

所以修改你的代码以更好地工作

答案 1 :(得分:1)

function User(fullName) {
  this.fullName = fullName.split(' ');


  Object.defineProperty(this, 'firstName', { 
    get: function() {
        return this.firstName = this.fullName[0];
    },

    set: function(newFisrtName) { 
        this.fullName[0] = newFisrtName;
    }
  });

  Object.defineProperty(this, 'lastName', {
    get: function() {
        return this.fullName[1];
    },

    set: function(newLastName) { 
        
	this.fullName[1] = newLastName;
    }   
  });

}

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

delete jone.lastName; 

jone.lastName = 'Mashow';

console.log(jone.fullName); 
console.log(jone.firstName); 
console.log(jone.lastName); 

实际上,在姓氏设置器中,您意外地将数组设置为字符串。这就是为什么它表现得如此。请参阅以上修改后的代码。