为什么setter方法对我的JavaScript对象中的其他变量没有影响?
问题描述:
有人可以请解释为什么在“setFirstName”setter方法已将“firstName”变量更改为“NewFirstName”后,对象中的“fullName”变量不会更改。我知道这个问题的正确答案,但我很困惑,为什么下面的解决方案不起作用。为什么setter方法对我的JavaScript对象中的其他变量没有影响?
This is a picture showing the below snippet being run
下面是代码:
<!DOCTYPE html>
<html>
<script>
var Person = function(firstAndLast) {
let firstName = firstAndLast.split(" ")[0];
let lastName = firstAndLast.split(" ")[1];
let fullName = firstName + " " + lastName;
// Getters
this.getFirstName = function() {
return firstName;
};
this.getLastName = function() {
return lastName;
};
this.getFullName = function() {
return fullName;
};
// Setters
this.setFirstName = function(first) {
firstName = first;
};
this.setLastName = function(last) {
lastName = last;
};
this.setFullName = function(name) {
fullName = name;
};
};
debugger;
var bob = new Person('Bob Ross');
console.log(bob.getFullName());
bob.setFirstName("NewFirstName");
console.log(bob.getFirstName());
console.log(bob.getFullName());
</script>
</html>
答
由于您只计算一次fullName
,它不会动态更新。
你不是真的想要一个变量fullName
,只是一个getter:
this.getFullName = function() {
return firstName + " " + lastName;
}
删除
let fullName = firstName + " " + lastName;
或者你可以保持你的变量和手动更新它在setFirstName
和setLastName
两个函数,但实际上这是获取者需要做的事情。
您的'fullname'变量在实例化过程中被评估一次。你会希望从getter而不是'fullname'本身返回'firstname +''+ lastname'。 – nilobarp