Table of Contents

Javascript - Call method

Definition

Calls (executes) a function and sets its this to the provided value

if the function has not be binded

, arguments can be passed as they are.

call(this) gives the ability to pass the current context (scope)

Example

Hello World

let nico = {
    name: "Nico",
    greet: function() {
        console.log("Hello "+this.name);
    }
};

// Outputs: "Change the world",
nico.greet(); 

// The world 
let world = {
    name: "world"
};

// bind this of the call function to the world object
// hello world
nico.greet.call(world); 

Basic

var boundFn = function () {
  return this.x;
};
 
boundFn.call( {x: 20} ); // 20

Call(this)

var x = 20
var boundFn = function () {
  return this.x;
};
 
boundFn.call( this ); // 20

Bind and Call

Let op: Bind and Call

var boundFn = function () {
  return this.x;
}.bind( {x: 10} );
 
boundFn(); // 10
boundFn.call( {x: 20} ); // still 10

Documentation / Reference