gpt4 book ai didi

javascript - 在 JavaScript 中调用类似属性的函数?

转载 作者:行者123 更新时间:2023-12-02 17:46:54 25 4
gpt4 key购买 nike

我在 MDN(Mozilla 开发者网络)的 JavaScript 教程上看到了这段代码(顺便说一句,读起来很精彩)。 MDN JavaScript Re-introduction

   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;
}

令我感兴趣的是函数的调用方式。典型的是();不用于在 Person 函数中进行函数调用。在 Person 函数中,我们看到:

this.fullName = personFullName;

用来代替

this.fullName = personFullName();

在这里,“personFullName”被用作变量或属性,而不是真正的函数。有人可以解释一下为什么会这样吗?

最佳答案

运行函数Person时不会调用这些函数,仅传递引用。

<小时/>

JavaScript 将函数视为一等公民,这意味着函数是像其他所有东西一样的对象:它们可以具有属性,可以保存在变量中,可以作为参数传递等。

这允许一些真正具有表现力的代码,看看这个:

function isEven(item) {
return item % 2 == 0;
}

alert([1, 2, 3, 4, 5, 6].filter(isEven));

Demo

首先创建一个函数并将其保存在名为 isEven 的变量中,然后我们将该函数传递给 Array.filter ,以防万一将每个元素传递到该数组中,并返回一个仅包含 isEven 返回 true 的元素的数组。

关于javascript - 在 JavaScript 中调用类似属性的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com