JS: Reflect.apply β
(new in ECMAScript 2015)
Reflect.apply(f, this-binding, argArray)-
- Call
fwith this (binding) of this-binding, and with arguments of elements in argArray. - Return the result.
- argArray is array or Array-Like Object.
function ff(a, b) { return a + b; } console.assert( Reflect.apply(ff, null, [1, 2]) === 3, ); // apply an arrow function console.assert( Reflect.apply((a, b) => (a + b), null, [1, 2]) === 3, ); // example of Reflect.apply with this-binding argument function ff(x, y) { this.dog = x; this.cat = y; } const jj = {}; Reflect.apply(ff, jj, [3, 4]); console.log(jj); // { dog: 3, cat: 4 } - Call
Purpose of Reflect.apply
Reflect.apply is created in ECMAScript 2015.
It fixes some problem of
because
Function.prototype.applyis confusing, because the actual call form isfName.apply. You need to understand this-binding and inheritance mechanism of JavaScript. Also, the dotted object/property relation is not the object parent/child relation. [see JS: Prototype and Inheritance]Function.prototype.applydoes not work if a function has a property"apply"or in its parent chain.Reflect.applydoes not have these problems.
/* comparison of Reflect.apply vs Function.prototype.apply */ console.log(Reflect.apply(Math.max, null, [24, 185, 53])); // 185 console.log(Math.max.apply(null, [24, 185, 53])); // 185