gpt4 book ai didi

javascript - JS 模块 : Difference between directly returning a function in an object and returning a function in an object returning a function

转载 作者:行者123 更新时间:2023-11-29 10:26:14 29 4
gpt4 key购买 nike

它是多余的,但我正在学习 JS,我想知道它是如何工作的。

  1. 直接从模块返回函数
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : test
}
}
  1. 使用函数返回一个函数
let func1 = function () {
let test = function () {
console.log("1");
}
return {
getTest : function () {
return test;
}
}
}

最佳答案

在第一种情况下,对象的 getTest 属性指向一个函数,所以这样调用它:

func1().getTest()

应该导致记录 1。

在第二种情况下,getTest 返回一个函数,该函数返回另一个函数,因此您还必须调用结果才能获得 1,这样:

func1().getTest()();

仅调用 getTest 将返回您的函数对象,而不是调用它。

关于javascript - JS 模块 : Difference between directly returning a function in an object and returning a function in an object returning a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58547177/

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