sveixq
Last Updated: February 25, 2016
·
1.544K
· heldrida

Javascript, use case examples for .bind(), .call() and .apply()

Hi,

I've tried to create a really basic example on .bind(), .call(), .apply() to showcase how to change context (or this):

// Skater Constructor
 function Skater(){
   console.log(arguments);
   this.name = arguments[0];
 }

 Skater.prototype.tricks = function() {

   var data = ["ollie", "flip", "kickflip"];
   var str = "";

   for(var i = 0; i < data.length; i++){
     str += ", " + data[i];
   };

   return this.name + " best tricks are" + str;

 }

 // Create new instance of skater
 var nyjah = new Skater("Nyjah Huston");

 // Output
 console.log( nyjah.tricks() );

 // Example of .bind(), to change context

 // Create new instance of skater
 var luan = new Skater("Luan Oliveira");

 // Output
 console.log( nyjah.tricks.bind(luan)() );

 // Example of .call(), to change context

 // Create new instance of skater
 var paul = new Skater("Paul Rodriguez", "arg1", "arg2");

 // Output
 console.log( nyjah.tricks.call(paul) );

 // Example of .apply(), to change context

 // Create new instance of skater
 var salabanzi = new Skater("Bastien Salabanzi", ["arg1", "arg2"]);

 // Output
 console.log( nyjah.tricks.apply(salabanzi, ['arg1', 'arg2']) );

Hope this helps!