Skip to content

Instantly share code, notes, and snippets.

@geekdenz
Created February 15, 2016 10:37
Show Gist options
  • Save geekdenz/3e8f36644a5b630767b4 to your computer and use it in GitHub Desktop.
Save geekdenz/3e8f36644a5b630767b4 to your computer and use it in GitHub Desktop.
Description of closures on a semi-useful function bind2.
'use strict';
function log() {
//document.getElementById('log').innerHTML += Array.prototype.join.apply(arguments, ["\n"]) + "\n\n";
console.log(arguments);
}
Function.prototype.bind2 = function (o) {
var fn = this;
log('closure this:', this, "\nfn:", fn);
return function () {
log('inner this:', this, "\nfn:", fn);
return fn.apply(o, arguments);
};
};
var obj = {bar: 'bar of obj'};
foo = foo.bind2(obj);
foo('buz');
log("------------\n");
Function.prototype.bind3 = function (o) {
log('bind3:', this);
return this.apply(o, arguments);
};
foo.bind3('bar3');
foo('calledBind3');
log("------------\n");
Function.prototype.bind4 = function (o) {
// doesn't work because of recursion!
//arguments.callee.apply(o, arguments);
};
function foo(a) {
console.log(this.bar + " &" + a);
}
foo.bind4('bar4');
foo('calledBind4');
/* Started writing this, in case I don't complete...
* https://www.linkedin.com/groups/121615/121615-6104378356734713858
Got interested in this problem to confirm my understanding of closures in JavaScript, which in my opinion makes JS one of the hardest languages I know about:
See https://jsfiddle.net/ynq8289b/
If you didn't have the inner function, this would refer to the window object, because that is the default if the function cannot find an object that is this in its current scope. So, bind3 would work on object functions, although not necessarily always, because this in JS is dynamic.
At the function call time this is the foo object with the (sort of) class Function. But in JS we have prototypal inheritance, so things are a bit awkward though logical (of course, because we are dealing with logic machines). So, at the call time of foo(), this is foo so fn becomes foo. However,
*/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment