JS: Reflect.apply (λ)
(new in ECMAScript 2015)
Reflect.apply(f, thisBinding, argArray)-
- Call
fwith this (binding) of thisBinding, 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.log(Reflect.apply(ff, null, [1, 2])); // 3 // apply an arrow function console.log(Reflect.apply(((a, b) => (a + b)), null, [1, 2])); // 3 // example of Reflect.apply with thisBinding argument function ff(a, b) { this.k1 = a; this.k2 = b; } const jj = {}; Reflect.apply(ff, jj, [3, 4]); console.log(jj); // { k1: 3, k2: 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