【发布时间】: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