问题描述
所以我得到了一个[200,599]的数组从promise返回,spread内的回调函数被传递给Function.apply.bind,但现在我迷路了。如何将[200,599]的数组分成x和y? apply.bind究竟是如何工作的?
So I get that an array of [200,599] is returned from the promise and the callback function inside spread is being passed into Function.apply.bind, but now I'm lost. How is the array of [200,599] split into x and y? How exactly does the apply.bind work?
function getY(x) {
return new Promise( function(resolve,reject){
setTimeout( function(){
resolve( (3 * x) - 1 );
}, 100 );
} );
}
function foo(bar,baz) {
var x = bar * baz;
// return both promises
return [
Promise.resolve( x ),
getY( x )
];
}
function spread(fn) {
return Function.apply.bind( fn, null );
}
Promise.all(
foo( 10, 20 )
)
.then(
spread( function(x,y){
console.log( x, y ); // 200 599
} )
)
推荐答案
.apply()
是函数对象的方法。像这样:
.apply()
is a method on function objects. Like so:
console.log(Math.max.apply(null, [1, 2, 3])); // 3
.apply()
接受两个参数,即上下文(目标函数内部会变成 this
)和一个可迭代的参数(通常是一个数组,但是参数
数组也有效)。
.apply()
accepts two arguments, the context (what would become this
inside of the target function) and an iterable of arguments (usually an array, but the arguments
array like also works).
.bind()
是函数对象的一个方法。像这样:
.bind()
is a method on function objects. Like so:
const x = {
foo: function() {
console.log(this.x);
},
x: 42
}
var myFoo = x.foo.bind({x: 5});
x.foo(); // 42
myFoo(); // 5
.bind()
获取一个上下文(将成为 this
),以及可选的其他参数,并返回一个新函数,上下文绑定,其他参数已锁定
.bind()
takes a context (what would become this
), and optionally, additional arguments, and returns a new function, with the context bound, and the additional arguments locked
自以来。 apply()
是一个函数,它可以与 .bind()
绑定,如下所示:
Since .apply()
is a function in on itself, it can be bound with .bind()
, like so:
Function.prototype.apply.bind(fn, null);
意味着此
.apply()
将是 fn
并且第一个参数为 .apply()
将是 null
。意思是它看起来像这样:
Meaning that the this
of .apply()
would be fn
and the first argument to .apply()
would be null
. Meaning that it would look like this:
fn.apply(null, args)
这会从数组中传播参数。
Which would spread the parameters from an array.
这篇关于function.apply.bind如何在以下代码中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!