Reflect.apply
calls a target function
it is a static method
const actualType = '???';
assert.equal(actualType, typeof Reflect.apply)
the 1st parameter
is a callable, e.g. a function
let fn;
assert.equal(Reflect.apply(fn, void 0, []), 42);
passing it a non-callable throws a TypeError
const applyOnUncallable = () =>
Reflect.apply(() => {}, void 0, []);
assert.throws(applyOnUncallable, TypeError);
the 2nd parameter
is the scope (or the `this')
class FourtyTwo {
constructor() { this.value = 42}
fn() {return this.value}
}
let instance = new FourtyTwo();
const fourtyTwo = Reflect.apply(instance.fn, ___, []);
assert.deepEqual(fourtyTwo, 42);
the 3rd parameter
must be an array (or array-like)
const thirdParam = 'should be array-like';
assert.doesNotThrow(() => Reflect.apply(() => void 0, null, thirdParam));
is an array of parameters passed to the call
let emptyArrayWithFiveElements = Reflect.apply(Array);
assert.deepEqual(emptyArrayWithFiveElements.fill(42), [42, 42, 42, 42, 42]);
example usages
simple function call
const fn = () => ':(';
assert.equal(Reflect.apply(fn, void 0, []), 'the return value');
call a function on an array
const fn = [].join;
assert.deepEqual(Reflect.apply(fn, [0, 23, 42], [1]), [23, 42]);
pass in the this
that the function to call needs
class Bob {
constructor() { this._name = 'Bob'; }
name() { return this._name; }
}
const bob = new Bob();
const scope = Bob;
assert.equal(Reflect.apply(bob.name, scope, []), 'Bob');
Links
spec
How this function is specified.
spec
How the 3rd parameter gets processed, as an `CreateListFromArrayLike`.
docs
mdn
The MDN docs for this function.
announcement
Announcement of this kata on twitter.