Skip to content

Instantly share code, notes, and snippets.

@codebanesr
Last active June 3, 2020 20:52
Show Gist options
  • Save codebanesr/bf5d978d6edc660991fd4425a00c5249 to your computer and use it in GitHub Desktop.
Save codebanesr/bf5d978d6edc660991fd4425a00c5249 to your computer and use it in GitHub Desktop.

Lets say pokemon world was real and we are pokemon catchers

let pokemonBall = function() {
  console.log(this.name, this.powers)
}
pokemonBall()

What will be the output of the above function. undefined! But what if we had a pokemon, with a real name and powers!. So lets go ahead and catch a pokemon. But how do we do that? Well in javascript world we have this unique thing called bind. So in our world we bind a pokemon to pokemonBall.

const cutePokemon = {
  name: "pikachu",
  powers: "electric/shock"
}

Now we have a pokemon and a pokemon ball, let's see if we can bind pokemon to pokemon ball

pokemonBall = pokemonBall.bind(cutePokemon)
pokemonBall()

Output pikachu electric/shock, YaY! Interesting Observation - bind doesnot modify the original function, instead it returns a new function that is bounded to the object. Thats why we have to assign the result of bind to a variable before using it.

Beware though call, bind and apply dont work with arrow functions, because arrow functions by design do not have a context.

Now lets leave the imaginary world and look at bind in depth, I will leave it to you to figure out what the code below is trying to explain. See you soon!

const obj = {
	name: "shanur",
	age: 25
}

function getUserDetails() {
	this.dob = "05/08/1995";
	this.name = "someoneelse"
	return {
		name: this.name,
		age: this.age,
		dob: this.dob
	}
}

The two lines will give exactly similar output, this gives us a way to remember bind functionality clearly console.log(getUserDetails.bind(obj)());

Object.assign(obj, {name: "someoneelse"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment