2/1/20

My Implementation of Javascript "Bind"

Recently i was asked on some interview to implement "bind". So i think i will make a post dedicated to bind implementation.

What is a purpose of "bind" anyway?

Well, everybody knows that when you use a javascript you must use "this" keyword very carefully. In some cases - "this" (which called also execute context) can seem to "loose" its original meaning and have some unexpected value instead...

Example

Lets say you have a "Person" object in your code:


function Person(name) {
  this.name = name;
}
Person.prototype.showName = function() {
  console.log(this.name);
}

let person = new Person('Chubaka')
person.showName();
// will print "Chubaka" as expected

Simple and clear...
But!
What will happen if we will try to execute this method in response of some event, say clicking on document?

function Person(name) {
  this.name = name;
}
Person.prototype.showName = function() {
  console.log(this.name);
}

let person = new Person('Chubaka')
document.onclick = person.showName;
// will print "undefined" (WHYYYY???)

Why? because "this"(inside showName function) is no more populated with "person" object.
Instead (if we will try to debug and look closer at this "this") - we will find that like any event - the this now populated with the target of event(which is document)
This is where "bind" might be helpfull:
It attaches the context to function for the future execution:

let person = new Person('Chubaka')
document.onclick = person.showName.bind(person);
// will print "Chubaka" again

Implementation

Here is my implementation of bind (i called it "mybind")


  Function.prototype.mybind = function (context) {
    const that = this;// 'this' here is instance of "function" object
    return function() {// this function will be called in response to "click" event
      that.call(context)  // here the context will be passed           
    }
  }

Do we still Need "bind" in the era of ES6?

My answer is - No
Here is why:
You can write the same functionality using modern ES6 syntax:


  class Person {
    constructor(name) {
      this.name = name;
      this.showName = () => {
        console.log(this.name);
      }
    }
  }

let person = new Person('Chubaka')
document.onclick = person.showName; 
// chubaka is here again 
// (and no 'bind' needed)

See you in the next article!

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...