Created
April 20, 2009 15:14
-
-
Save robertsosinski/98576 to your computer and use it in GitHub Desktop.
Understanding how to bind scope in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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