Javascript this.fullName=fullName&;的构造函数逻辑;split()方法
谁能给我解释一下: 我们有两个相似的代码。它们的功能是相同的。但是在第一段代码中,我们得到了一个正常的结果,而在下一段代码中,我们得到了一个非常奇怪的结果 我不明白为什么结果不同,因为我们只改变了值拆分的变量-从第一种情况下的var split中的声明到下一种情况下的this.fullName prop中的直接更改。并在下面相应的代码中使用它们Javascript this.fullName=fullName&;的构造函数逻辑;split()方法,javascript,constructor,get,set,Javascript,Constructor,Get,Set,谁能给我解释一下: 我们有两个相似的代码。它们的功能是相同的。但是在第一段代码中,我们得到了一个正常的结果,而在下一段代码中,我们得到了一个非常奇怪的结果 我不明白为什么结果不同,因为我们只改变了值拆分的变量-从第一种情况下的var split中的声明到下一种情况下的this.fullName prop中的直接更改。并在下面相应的代码中使用它们 this.fullName = fullName; var split = this.fullName.split(' '); 换 this.full
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
-------上述代码的第二个变体--------
第二个声明中的问题在于此方法
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现在是一个字符串而不是数组,这就是为什么第一个声明有效,因为您使用了另一个变量split,并且不更改它,而是保留数组
因此,修改代码以更好地工作第二个声明中的问题在于此方法
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现在是一个字符串而不是数组,这就是为什么第一个声明有效,因为您使用了另一个变量split,并且不更改它,而是保留数组
因此,请修改代码以更好地工作
函数用户(全名){
this.fullName=fullName.split(“”);
Object.defineProperty(这是'firstName',{
get:function(){
返回this.firstName=this.fullName[0];
},
集合:函数(newFirstName){
this.fullName[0]=newFirstName;
}
});
Object.defineProperty(此“lastName”{
get:function(){
返回此。全名[1];
},
集合:函数(newLastName){
this.fullName[1]=newLastName;
}
});
}
var jone=新用户(“jone Coven”);
删除jone.lastName;
jone.lastName='Mashow';
console.log(jone.fullName);
console.log(jone.firstName);
console.log(jone.lastName)代码>
函数用户(全名){
this.fullName=fullName.split(“”);
Object.defineProperty(这是'firstName',{
get:function(){
返回this.firstName=this.fullName[0];
},
集合:函数(newFirstName){
this.fullName[0]=newFirstName;
}
});
Object.defineProperty(此“lastName”{
get:function(){
返回此。全名[1];
},
集合:函数(newLastName){
this.fullName[1]=newLastName;
}
});
}
var jone=新用户(“jone Coven”);
删除jone.lastName;
jone.lastName='Mashow';
console.log(jone.fullName);
console.log(jone.firstName);
console.log(jone.lastName)代码>