gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:35:45 25 4
gpt4 key购买 nike

有人可以解释一下吗:

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

我不明白为什么结果不同,因为我们只更改了值拆分的变体 - 从第一种情况下 var split 中的声明 变量 更改为直接在下一个中更改当前的 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

最佳答案

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);

实际上,在姓氏 setter 中,您不小心将数组设置为字符串。这就是为什么它会表现得如此。请参阅上面修改后的代码。

关于javascript - this.fullName = fullName & split() 方法的构造函数逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com