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. array can be array-like object.

// example of using f.apply
function ff() { return this; }
const x2 = {kk:373};
console.log ( ff.apply( x2 ) ); // { kk: 373 }

Example with 2 arguments:

// example of using apply

function ff(a,b) {
    this.x = a;
    this.y = b;
}

const x3 = {};

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

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

Second arg of apply can be array-like object.

function ff(a,b) {
    this.x = a;
    this.y = b;
}

const x3 = {};

// 2nd arg of apply can be array-like object
ff.apply(x3, {0:7,1:8,length:2});

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 might want to use Reflect.apply instead.

[see JS: Reflect.apply]

Reference

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

Function Topic

  1. Define Function
  2. Functional Programing
  3. Arrow Function
  4. Function Parameters
  5. f Declaration vs Expression
  6. Closure
  7. Function Call, Apply, Bind
  8. Function Argument Default Value
  9. Function Rest Parameters
  10. Function Argument Destructure
  11. Function Object
  12. Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc