繁体   English   中英

JavaScript从构造函数中调用方法

[英]JavaScript calls to methods from within constructors

我正在MDN网站上阅读有关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()函数,只需输入它们的名称并将它们作为值分配给上面代码中所述的两个变量即可(此。 fullName和this.fullNameReversed)。 这一点对我来说很清楚,但是我的问题是,为什么省略了personFullName和personFullNameReversed旁边的括号? 它不应该说:

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

在MDN网站的示例中,它的显示方式让我感觉好像Person构造函数的fullName和fullNameReversed属性指向某些已经声明的全局变量,而不是在Person构造函数之外声明的函数。

如果添加括号,则将调用函数并将其返回值分配给this.fullNamethis.fullNameReversed

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

它是在分配功能,而不是功能的结果。 等效于:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM