【问题标题】:Why doesn't the setter method have any effect on other variables in my JavaScript object?为什么 setter 方法对我的 JavaScript 对象中的其他变量没有任何影响?
【发布时间】:2017-10-19 09:24:53
【问题描述】:

谁能解释一下为什么在“setFirstName”设置器方法将“firstName”变量更改为“NewFirstName”后我的对象中的“fullName”变量没有改变。我知道这个问题的正确答案,但我很困惑为什么以下解决方案也不起作用。

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 返回 firstname + ' ' + lastname 而不是 fullname 本身。

标签: javascript oop object constructor


【解决方案1】:

因为您只计算了一次fullName,所以它不会动态更新。

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

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

删除

let fullName = firstName + " " + lastName;

或者,您可以保留变量并在 setFirstNamesetLastName 函数中手动更新它,但实际上这是 getter 要做的事情。

【讨论】:

  • 感谢您的澄清。请问这种行为是否在其他面向对象编程语言(如 Java)中很常见,或者这是 JavaScript 的一个怪癖?
  • 这很常见。在 Java 中,这与在构造函数中设置 fullName 属性相同,它不会自动更新 - 您是在说“当您点击此代码时,将这些字符串按原样连接起来”。将使用吸气剂以与我建议的相同方式解决此问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 2014-07-02
  • 1970-01-01
  • 2013-05-12
  • 2010-12-07
相关资源
最近更新 更多