2017-10-19 50 views
0

有人可以请解释为什么在“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>

+0

您的'fullname'变量在实例化过程中被评估一次。你会希望从getter而不是'fullname'本身返回'firstname +''+ lastname'。 – nilobarp

回答

2

由于您只计算一次fullName,它不会动态更新。

你不是真的想要一个变量fullName,只是一个getter:

this.getFullName = function() { 
    return firstName + " " + lastName; 
} 

删除

let fullName = firstName + " " + lastName; 

或者你可以保持你的变量和手动更新它在setFirstNamesetLastName两个函数,但实际上这是获取者需要做的事情。

+0

谢谢澄清。请问这种行为在Java等其他面向对象编程语言中是否很常见,或者这是JavaScript的怪癖吗? – phao5814

+0

这很常见。在Java中,这与在构造函数中设置'fullName'属性相同,它不会自动更新 - 你说“当你打这个代码时,将这些字符串按照他们现在的形式连接起来”。我会用同样的方法来解决这个问题。 – UncleDave

+0

了解 - 感谢您的回答。 – phao5814

相关问题