Skip to content

Instantly share code, notes, and snippets.

@abhiomkar
Created September 18, 2015 10:42
Show Gist options
  • Save abhiomkar/c7013870c009c1096970 to your computer and use it in GitHub Desktop.
Save abhiomkar/c7013870c009c1096970 to your computer and use it in GitHub Desktop.
Early Binding & Late Binding in JavaScript
// Early Binding vs Late Binding
// Early Binding
var sum = function(a, b) {
return a + b;
};
var x = 5, y = 6;
var sum5n6 = sum.bind(null, x, y);
x = 10;
y = 5;
console.log("with Early Binding -->", sum5n6());
// Late Binding
var sum2 = function(p) {
return p.x + p.y;
};
var x = 5, y = 6;
var n = {x: x, y: y};
var sumLate = sum2.bind(null, n);
n.x = 10;
n.y = 5;
console.log("Late Binding -->", sumLate());
@kaizer1v
Copy link

kaizer1v commented Oct 19, 2018

Basically a way of saying - Rather than binding a function with values which cannot be changed later - bind with a value that you can change later i.e. bind the function with an Object instead - because you can always alter the properties of an object after it has been defined.

@RogerTarani
Copy link

Thanks for this simple and clear example.
Maybe you could add the result:

with Early Binding --> 11
Late Binding --> 15

Why with js, defining a function triggers the message "undefined"?...

I read that bind is deprecated in favor of or (??). Or maybe it's related to jQuery? (which is a js library)
https://www.w3schools.com/jquery/event_bind.asp
What is the truth?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment