Skip to content

Instantly share code, notes, and snippets.

@detro
Created February 12, 2012 21:20
Show Gist options
  • Save detro/1810899 to your computer and use it in GitHub Desktop.
Save detro/1810899 to your computer and use it in GitHub Desktop.
JS Invocation Patterns
var foo, obj, Constructor, ClosuredScope;
aVariable = "I'm a String in a global (attached to 'window')";
// 'foo', but no 'bar'
foo = function(callMessage) {
console.log("\n\033[0;32m" + callMessage + " {\033[0m"); //< console.log(callMessage + "{");
console.log(aVariable);
console.log(this.aVariable);
console.log(window.aVariable);
if (typeof(this.that) != "undefined" && this.that.aVariable) {
console.log(this.that.aVariable + " (passed via \033[0;31m'that'\033[0m)");
}
if (this === window) {
console.log("Here \033[0;31m'this'\033[0m resolves to \033[0;31m'window'\033[0m");
}
console.log("\033[0;32m}\033[0m\n"); //< console.log("}");
};
// Function Invocation Pattern
foo("*** Proving the 'Function Invocation Pattern' ***");
// Method Invocation Pattern
obj = {
aVariable : "I'm a String in an object (i.e. scope/'this')",
foo : foo
};
obj.foo("*** Proving the 'Method Invocation Pattern' ***");
// Constructor Invocation Pattern + Prototype Inheritance
Constructor = function(s) {
this.aVariable = s;
};
Constructor.prototype.foo = foo;
obj = new Constructor("I'm a String in an object (i.e. scope/'this'), assigned via a Constructor");
obj.foo("*** Proving the 'Constructor Invocation Pattern + Prototype Inheritance' ***");
// Constructor Invocation Pattern + Closure
ClosuredScope = function(s) {
var aVariable = s;
this.aVariable = s;
this.fooWrapper = function(m) { foo(m); console.log(aVariable + " (from the wrapper)"); };
this.fooOriginal = foo;
};
obj = new ClosuredScope("I'm a String in an object (i.e. scope/'this'), accessible via Closure");
obj.fooOriginal("*** Proving the 'Constructor Invocation Pattern + Closure' (original) ***");
obj.fooWrapper("*** Proving the 'Constructor Invocation Pattern + Closure' (wrapper) ***");
// Apply Invocation Pattern
foo.apply({
aVariable : "I'm a String set via the 'apply' method: scope/'this' is passed to 'apply()'"
}, ["*** Proving the 'Apply Invocation Pattern' ***"]);
// 'that' = 'this' Invocation Pattern
ClosuredScope = function(s) {
this.aVariable = s;
return {
aVariable : this.aVariable,
that : this,
fooThat : foo
};
};
obj = new ClosuredScope("I'm a String set in another Closure");
obj.fooThat("*** Proving the 'That = This Invocation Pattern' ***");
phantom.exit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment