【问题标题】:JavaScript callback function(reference) accepting an argument without constructorJavaScript 回调函数(引用)接受没有构造函数的参数
【发布时间】:2019-09-21 00:01:15
【问题描述】:

Test 返回一个promise,随后'then'方法的回调被赋予函数test2,该函数console.logs字符串“hello”如预期的那样。

但是,test2 作为回调接受“hello”作为“someString”参数使用函数引用而不是通过在“then”方法中显式编写回调的方式的名称(如果有的话)是什么使用构造函数或者它在幕后如何工作?

async function test(){
 return "hello"
}

function test2(someString){
    console.log(someString);
}
//Here test2 accepts the return from test() which is "hello" without it being explicitly fed into test2 e.g. test2(arg)
test().then(test2);

【问题讨论】:

  • 我不明白问题是什么。您能否说明test2 作为回调接受“hello”作为“someString”参数的方式是什么意思?
  • 参数是隐式传递的。 JavaScript 是弱类型的,可以省略参数,并且您可以传递函数期望的更多参数 - test2 只是对 Promise.then 内部调用的函数的引用,并带有解析的值。当您显式编写 .then((res) => test2(res)) 时,您还传递了一个函数引用。
  • 你知道构造函数是用来初始化一个类的实例的函数吗?
  • @briosheje then() 方法被赋予 test2 函数作为回调,问题是它如何能够接受 'someString' 参数
  • @goodness Li357 上面已经回答了你的问题;)

标签: javascript constructor callback arguments es6-promise


【解决方案1】:

这里test2 的类型是functionthen() 会发现这是一个函数,并且可以像我们通过从先前的 promise 传递结果参数来适当地并且可以轻松地调用该函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2014-06-30
    • 2018-05-30
    相关资源
    最近更新 更多