JSFiddle - React, Tailwind, and code Playground
HTML
<button onclick="examples()">Run Examples</button>
<button onclick='getElementById("log").innerHTML=""'>Clear Log</button>
<br>
<div id="log"></div>
JavaScript
// collected by Troy Whorten from examples in Cody Lindley article:
// "Fully Understanding the this Keyword" which can be found here:
// http://code.tutsplus.com/tutorials/fully-understanding-the-this-keyword--net-21117
// basic example
function logIt(logString) {
el = document.createElement("span");
console.log(logString);
el.innerHTML = logString;
document.getElementById("log").appendChild(el);
document.getElementById("log").appendChild(document.createElement("br"));
}
function examples() {
var cody = {
living: true,
age: 23,
gender: 'male',
getGender: function () {
return this.gender;
}
};
logIt(cody.getGender()); // logs 'male'
logIt("end basic example");
//change of context example
var foo = 'foo';
var myObject = {
foo: 'I am myObject.foo'
};
var sayFoo = function () {
logIt(this.foo);
};
myObject.sayFoo = sayFoo; //logs "I am myObject.foo"
myObject.sayFoo(); // logs "foo"
sayFoo();
logIt("end context change example");
// nested function example
var myObject = {
func1: function () {
logIt(this); //logs myObject
varfunc2 = function () {
logIt(this); //logs window, and will do so from this point on
varfunc3 = function () {
logIt(this); //logs window, as it’s the head object
}();
}();
}
};
myObject.func1();
logIt("end nested functions example");
//example with passing function as argument
var foo = {
func1: function (bar) {
bar(); //logs window, not foo
logIt(this); //the this keyword here will be a reference to foo object
}
};
foo.func1(function () {
logIt(this);
});
logIt("end function as argument example");
// using variable "that" to keep track of scope
var myObject = {
...