JS: Function.prototype.apply

By Xah Lee. Date: . Last updated: .

f.apply(obj) → evaluate f() with f's this keyword having value of obj.

f.apply(obj, array) → evaluate function f with f's this keyword have value of obj, and elements of the array array is passed to the function as arguments.

// example of using f.apply

function ff() {
    return this;
}

const x2 = {k1:1};

console.log (
    ff.apply( x2 )
);
// { k1: 1 }

Example with 2 arguments:

// example of using f.apply

function ff(x,y) {
    this["x"] = x;
    this["y"] = y;
}

const x3 = {};

ff.apply(x3, [7,8]);

console.log( x3 );
// { x: 7, y: 8 }

The “apply” method can be used to get the max value of a array. See: JS: Get Max/Min Value of Array.

Reflect.apply

For ES2015, you should use Reflect.apply, because it has clearer syntax and does not depends on the “prototype” inheritance.

[see JS: Reflect.apply]

Reference

ECMAScript 2015 §Fundamental Objects#sec-function.prototype.apply

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth