【问题标题】:JavaScript calls to methods from within constructorsJavaScript 从构造函数中调用方法
【发布时间】:2013-05-08 00:40:30
【问题描述】:

我在 MDN 网站上阅读 re-introduction to JavaScript 并在自定义对象部分看到了这个:

function personFullName() {
    return this.first + ' ' + this.last;
}
function personFullNameReversed() {
    return this.last + ', ' + this.first;
}
function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = personFullName;
    this.fullNameReversed = personFullNameReversed;
}

它在 MDN 网站上说,您可以在 Person 构造函数中引用 personFullName() 和 personFullNameReversed() 函数,只需键入它们的名称并将它们作为值分配给上面代码中所述的两个变量(this.fullName 和 this.fullNameReversed)。这对我来说都很清楚,但我的问题是为什么 personFullName 和 personFullNameReversed 旁边的括号被省略了?是不是应该说:

this.fullName = personFullName();
this.fullNameReversed = personFullNameReversed();?

从 MDN 网站的示例中呈现的方式,我觉得 Person 构造函数中的那些 fullName 和 fullNameReversed 属性指向一些已经声明的全局变量,而不是在 Person 构造函数之外声明的函数。

【问题讨论】:

    标签: javascript function methods constructor custom-object


    【解决方案1】:

    如果添加括号,您将调用函数并将它们的返回值分配给this.fullNamethis.fullNameReversed

    代码是引用函数,而不是调用它们。

    【讨论】:

    • 因此,如果我从 personFullName() 函数中添加方括号 this.first 实际上会首先指向全局变量,而不是指向 Person 构造函数的属性 first,因此会返回使用的结果一个全局变量而不是来自 Person 构造函数的局部变量?
    • @SineLaboreNihil:是的,正确。如果添加了括号,this.fullName 根本就不是函数,而是字符串“undefined undefined”。 this.fullName = personFullName() 行(带括号)将在执行该行代码时调用 personFullName。该调用将从未定义的firstlast 全局变量构建一个字符串。在这里查看:jsfiddle.net/h9N6Y
    • 非常感谢您为我解决这个问题。对此,我真的非常感激。 :)
    【解决方案2】:

    这是分配函数,而不是函数的结果。相当于:

    function Person(first, last) {
        this.first = first;
        this.last = last;
        this.fullName = function () {
            return this.first + ' ' + this.last;
        };
        this.fullNameReversed = function () {
            return this.last + ', ' + this.first;
        };
    }
    

    所以现在你可以这样做了:

    var jack = new Person('Jack', 'Smith');
    console.log(jack.fullName()); // Jack Smith
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2015-10-10
      • 2013-08-10
      • 2016-05-31
      • 1970-01-01
      • 2015-10-01
      • 2011-10-22
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多