this explained

by Arnaud Buchholz

CSS

body {
  font: 16px arial, sans-serif;
}

.title {
  font: bold 32px arial, sans-serif;
}

.section {
  padding-top: 24px;
  font: italic 24px arial, sans-serif;
}

.functionName {
  display: inline-block;
  padding-right: 8px;
  color: orange;
}

JavaScript

// Logging helper
function log(text) {
	var line = document.body.appendChild(document.createElement("div"));
  line.appendChild(document.createTextNode(text));
  return line;
}

function res(functionName, value) {
	var line = document.body.appendChild(document.createElement("div")),
  		functionTag = line.appendChild(document.createElement("span"));
	functionTag.setAttribute("class", "functionName")
  functionTag.appendChild(document.createTextNode(functionName));
	line.appendChild(document.createTextNode(value));
}

log("this explained").className = "title";

window.value = "global value"; // usually should be a var but JSFiddle encapsulates it...

function myStrictFunction () {
	"use strict";
	try {
		res("myStrictFunction", this.value );
  } catch (e) {
  	res("myStrictFunction", "Exception: " + e);
  }
}

function myFunction () {
	try {
		res("myFunction", this.value );
  } catch (e) {
  	res("myFunction", "Exception: " + e);
  }
}

log("Calling the function the 'simplest' way possible:").className = "section";
myFunction(); // this is not explicitely set, it will fallback to window
myStrictFunction(); // this is not explicitely set, it will be undefined

log("Inside an object").className = "section";
var oObject = {
	value: "from Object",
  method: myFunction
};
oObject.method(); // this will be set to the 'left' part of the .

var oStrictObject = {
	value: "from strict Object",
  method: myStrictFunction
};
oStrictObject.method(); // this will be set to the 'left' part of the .

log("Calling with call/apply").className = "section";
myFunction.call({
	value: "parameter Object"
}); // Will be the same result with apply: the first parameter becomes this
myStrictFunction.call({
	value: "parameter strict Object"
});  // Will be the same result with apply: the first parameter becomes this

log("Special types used as this (null)").className = "section";
myFunction.call(null); // any falsy value leads to the fallback to window
myStrictFunction.call(null); // null...