JSFiddle - React, Tailwind, and code Playground

by danShumway

JavaScript

//Showing off this abuse.


/*-------
What isn't "this"?
--------*/

/*
//Make an object.
function Cat() { 
    var speak = function(){ return "Meow!"; };
    
    alert(speak);
    //alert(this.speak);
}

//So var and this are two different things.
var myCat = new Cat();
*/

/*-----------
This refers to the context of the function.
-----------*/

/*
//Let's make a function in the main window.
function speak() { return "Meow!"; };

function Cat() {
     alert(this.speak);   
}

//Now let's call our object.  What happened?
var myCat = new Cat();//Doesn't work
//Cat();//Works
*/

/*--------------
What exactly is this?
--------------*/

/*
//Let's make an object using a different method.
function Cat() { 
    this.speak = function(){ return "Meow" };
}

//All that new does is - 
//create an empty object literal.
//Run the method you pass in afterwords with this set to the proper context (the object just created)

//var myCat = {};
//Cat.call(myCat);

//alert(myCat.speak());

//When I 'accidentally' just call the function, a variable gets created in global context.
Cat();
//alert(speak());

//Explanation of this.

//this is a global variable.
//Whenever I call a method, this first gets set to my current context, then the method gets called
//A chart would help here.
//This means that I don't actually know what this is going to be until after I call the method.

var cat = Function("var cat = 3; return cat;");
alert(cat());

*/

//A cool thing - stealing functions

/*function Cat(){
    this.mySound = "meow";
    
    this.speak = function() {
        alert("The cat says: " + this.mySound);
    }
}

function Dog(){
    this.mySound = "woof";
    
    this.speak = function() {
        alert("The dog says: " + this.mySound);//References are preserved though, so if I pass the cat to the dog, and use var instead, it preserves that it says meow.  That could be interesting to touch on.
    }
}

var myCat = new Cat();
var myDog = new...