Skip to content

Instantly share code, notes, and snippets.

@JoeShep
Created April 11, 2016 23:42
Show Gist options
  • Save JoeShep/a0625c5b98b1f5b88f6692bb4702b5a0 to your computer and use it in GitHub Desktop.
Save JoeShep/a0625c5b98b1f5b88f6692bb4702b5a0 to your computer and use it in GitHub Desktop.
This is this, or something
//******************************************************************************************************************
// This will break if you run it as is. You have to commment out all of the sections except the one you want to run.
//******************************************************************************************************************
/*
Example one: call site and call stack
*/
var fubar = "42";
function baz() {
console.log( "baz" );
bar();
}
function bar() {
console.log( "bar" );
foo();
}
function foo() {
var fubar = "13";
console.log( "foo" );
console.log( this );
console.log( this.fubar );
}
baz(); //logs 42
// The original call site is the call to baz();
// The execution context is the Window object.
// The same as calling window.baz(). THIS holds the execution context, which is always at the original call site.
/*
Example two: context objects
*/
function foo() {
console.log("this", this );
console.log( "this.a", this.a );
}
var obj = {
a: 2,
foo: foo
};
obj.foo(); //logs the object and 2
// The execution context is obj.foo. We've now gone down one contextual level.
// obj.foo() is the call site. obj is the execution context.
// "foo: foo" holds a reference to the foo function (note that it's not in quotes, so we know it's a variable of some kind
/*
Example three: context objects
*/
function foo() {
console.log( this.a );
}
var obj2 = {
a: 42,
foo: foo
};
var obj1 = {
a: 2,
obj2: obj2
};
obj1.obj2.foo();
/*
Example four: losing original binding
*/
function foo() {
console.log( this.a );
}
var obj = {
a: 2,
foo: foo
};
var bar = obj.foo;
var a = "global warming";
obj.foo();
bar();
/*
Example five: losing original binding with callbacks
*/
function foo() {
console.log( this.a );
}
function doFoo(fn) {
fn();
}
var obj = {
a: 2,
foo: foo
};
var a = "oops, global";
doFoo( obj.foo );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment