thisInJavaScript

Solution to the, understanding `this`, exercise.

by Niranjan Borawake

JavaScript

const javaScriptMessage = {
  language: 'JavaScript',
  message: 'I owe you.'
};

function printMessage() {
  console.log(`Hey ${this.language}...! ${this.message}`)
}

let printJavaScriptMessage = printMessage.bind(javaScriptMessage);
printJavaScriptMessage(); // Hey JavaScript...! I owe you.

// Now let's assume we don't have `bind`
Function.prototype.bind = null;

// Below line will throw - Uncaught TypeError: printMessage.bind is not a function

// printJavaScriptMessage = printMessage.bind(javaScriptMessage);

// Can you try to implement `bind` and prove you understand `this` in JavaScript.

Function.prototype.bind = function(context) {
  const functionToBind = this;
  return function() {
    functionToBind.call(context);
  }
}

// Hoping this works post implementation
printJavaScriptMessage = printMessage.bind(javaScriptMessage);
printJavaScriptMessage(); // Hey JavaScript...! I owe you.