【发布时间】:2017-12-22 12:34:43
【问题描述】:
谁能解释一下:
我们有两个相似的代码。它们的功能是相同的。但是在第一个代码中我们有一个正常的结果,而在下一个代码中 - 非常奇怪。
我不明白为什么结果不同,因为我们只更改了值拆分的变量 - 从 var split 中的声明 变量 在第一种情况下改为 direct在下一个中更改当前的 this.fullName 属性。并在下面的相应代码中使用它们。
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
【问题讨论】:
标签: javascript constructor get set