Skip to content

Instantly share code, notes, and snippets.

@m3talsmith
Last active August 29, 2015 14:06
Show Gist options
  • Save m3talsmith/917e031502d6d5b40f86 to your computer and use it in GitHub Desktop.
Save m3talsmith/917e031502d6d5b40f86 to your computer and use it in GitHub Desktop.
Showing the principle of javascript scope binding
var bob = (function (name) {
var char = {
name: name,
say: function (message) { this.logger(this.name + " says: " + message); },
logger: function (message) { console.log(message); }
};
return char;
})("Bob");
bob.say("hi"); // Bob says: hi
bob.name = "Robert";
bob.say("hi"); // Robert says: hi
bob.logger = function (message) { console.log("[" + Date.parse("01/01/2014") + "]", message); };
bob.say("hi"); // [1388559600000] Robert says: hi
var logger = function (message) {console.log(message);};
var Character = function (name) {
this.name = name;
this.say = function (message) { logger(this.name + " says: " + message); }
};
var bob = new Character("Bob");
bob.say("hi"); // Bob says: hi
var date = Date.parse("01/01/2014");
logger = function (message) {console.log("[" + date + "]", message);};
bob.say("hello again"); // [1388559600000] Bob says: hello again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment