4 Different this context

by jessekinsman

JavaScript

/*
4 Different ways to set this context
*/
 
 
 function foo () {
 	console.log(this);
 }

 var o2 = {bar: "implicitly set bar", foo: foo};
 
// Implicity binding. Binds to the object that it is called from
o2.foo();

//explicity binding with apply() or call()
var o3 = {bar: "explicity set bar"};
foo.apply(o3);
foo.call(o3);

// with bind (essentially using apply())
//var fooWithBind = foo.bind(o3);
//fooWithBind();

// Default to global scope
this.bar = "bar in global";
foo();

//This is a global scope example. This is the window object
function testThisScope(input) {
	function getInput() {
    return this;
  }
  return getInput;
}
 var test = testThisScope("yes this is the global function scope");
 console.log("test: " + test());
 console.log(this);
 
/* Using the New Keyword creates an empty object */
function foo(bar){
	this.bar = bar;
  console.log(this.bar);
}
var test = new foo("bar using new");
console.log("bar is undefined on global " + this.bar);