spabloramirez
1/29/2015 - 12:48 PM

#this.js

//THIS (invoker)
var obj = {
  prop:"value"
};
function func(param){	
  console.log(this);    
  if(param)
     console.log(this[param]); 
};

//whes called as a method
obj.func();//Object {prop: "value", func: function}
(obj.func)()//same

//when called as a function
func();//Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
(0 || false || obj.func)();//same:(a.method || b.method)() does not pass proper THIS.

//explicit invoker (CALL)
func.call(obj);//Object {prop: "value", func: function}
func.call(obj,'prop')//value: add arguments to call

//explicit invoker (APPLY)
//is same as func.call, but it accepts an array of arguments instead of a list.
var arrArguments = ['prop'];
func.apply(obj,arrArguments);

//In new
//Create this = {}.
//The function then runs and may change this, add properties, methods etc.
//The resulting this is returned.

function MyClass() {
  this.name = 'Mousie'
  return { name: 'Godzilla' }  // we can rewrite THIS returning another object
}
var obj = new MyClass();
console.log( obj.name )  // Godzilla