Javascript - Difference between bind, apply and call

var a = 10; // Global Variable function f(x) { // Function that accepts a variable x as parameter console.log(this.a, x); } // normal call // - this.a is 10 because Global Variable // - x = 1 // prints: `10 1` (or `undefined 1` if you are running it in node) f(1); // bind var g = f.bind({a: 20}); // bind CREATES a NEW function with `this.a = 20` // then you will need to execute the function separately g(2); // executing the new created function with `x = 2`, prints: `20 2` // or f.bind({a: 30})(3); // prints: `30 3` // apply f.apply({a: 40}, [4]); // apply CALLS the function with `this.a = 40` but you give ARRAY params // prints: `40 4` // call f.call({a: 50}, 5); // call CALLS the function with `this.a = 50` but requires INDIVIDUAL params // prints: `50 5`
Difference between Function.prototype.bind, Function.prototype.apply and Function.prototype.call.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.