Skip to content

Instantly share code, notes, and snippets.

@robertsosinski
Created April 20, 2009 15:14
Show Gist options
  • Save robertsosinski/98576 to your computer and use it in GitHub Desktop.
Save robertsosinski/98576 to your computer and use it in GitHub Desktop.
Understanding how to bind scope in JavaScript
window.scope = "window";
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
object = {
scope: "object",
run: function() {
// self-executing anonymous function with binding
(function(word) {
console.log(word + " " + this.scope)
}).bind(this)("hello");
// self-executing anonymous function without binding
(function(word) {
console.log(word + " " + this.scope)
})("hello");
// anonymous function with binding
bound_af = function(word) {
console.log(word + " " + this.scope)
}.bind(this);
bound_af("hello");
// anonymous function without binding
unbound_af = function(word) {
console.log(word + " " + this.scope)
}
unbound_af("hello");
// named function with binding
function bound_nf(word) {
console.log(word + " " + this.scope)
}
bound_nf.bind(this)("hello");
// named function without binding
function unbound_nf(word) {
console.log(word + " " + this.scope)
}
unbound_nf("hello");
}
}
object.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment