JS: Function.prototype.call

By Xah Lee. Date: . Last updated: .

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

f.call(obj, arg1, arg2 …) → evaluate f(arg1, arg2 …) with f's this keyword having value of obj.

〔►see JS: “this” Binding

// shows what f.call(arg) is doing

function ff() { return this; }

const obj = {};

console.log(
    ff.call(obj) === obj
); // true

Example with arguments.

function ff(a, b) { return a + b; }

console.log(
 ff.call(undefined, 3, 4) === 7
);
// true

Reflect.apply

For ES2015, you should use Reflect.apply instead.

f.call(obj)

is same as

Reflect.apply ( f , obj, [] )

// show f.call(arg) and Reflect.apply ( ff , arg, [] ) are same

function ff() { return this; }

const obj = {};

console.log(
 ff.call(obj) === obj
);

// true

console.log(
 Reflect.apply ( ff , obj, [] ) === obj
);
 // true

and

f.call(obj, arg1, arg2 …)

is same as

Reflect.apply ( f , obj, [arg1, arg2 …] )

// show f.call(arg) and Reflect.apply ( ff , arg, [] ) are same

function ff(a, b) { return a + b; }

console.log(
 ff.call(undefined, 3, 4) === 7
);

// true

console.log(
 Reflect.apply ( ff , undefined, [3, 4] ) === 7
);
 // true

〔►see JS: Reflect.apply

Reference

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

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
Like what you read? Buy JavaScript in Depth