有人可以请解释为什么在“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'变量在实例化过程中被评估一次。你会希望从getter而不是'fullname'本身返回'firstname +''+ lastname'。 – nilobarp