Skip to content

Instantly share code, notes, and snippets.

@prateekjadhwani
Created March 22, 2016 19:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save prateekjadhwani/bbc4f09f720f5698e691 to your computer and use it in GitHub Desktop.
Save prateekjadhwani/bbc4f09f720f5698e691 to your computer and use it in GitHub Desktop.
Difference between bind(), apply() and call()
var a = 10; // A Global Variable
function p(z) {
// a normal function that
// accepts a variable z as a parameter
console.log(this.a, z);
}
// normal call
// this.a is 10 because GLOBAL variable
// and z = 1
p(1);
// bind
var b = p.bind({a:20}); // bind CREATES a new function with `this.a = 20`
// then you will need to execute the function separately
b(2); // executing the new created function with `z = 2`
// or
p.bind({a:30})(3); // executing the function this way
p.apply({a:40}, [4]); // apply CALLS the function with `this.a = 40` but you give ARRAY params
p.call({a:50}, 5); // call CALLS the function with `this.a = 50` but requires INDIVIDUAL params
// The Output is
// 10 1 ( or `undefined 1` if you are running it in node)
// 20 2
// 30 3
// 40 4
// 50 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment