JSFiddle - React, Tailwind, and code Playground

by danShumway

JavaScript

//What usually happens
function Box(){
    var x = 5;
    
    //Everything just works
    this.incrementX = function() {
        x++; //Works, but I can't access x outside of the object.
    }
}

var myBox = new Box();
alert(myBox.x); //undefined

//------------------------------------------------------------

//Also will work.
function Box2(){
    this.x = 5;
    
    this.incrementX = function() {
        x++; //Works, and x is publicly accessible.
    }
}

var myBox2 = new Box2();
alert(myBox2.x); //5

//-------------------------------------------------------------

//So the normal explanation everyone gives is: use "this" for public variables, and "var" for private ones.
//The problem is, that it doesn't explain what the keywords actually do.
//Javascript pretends to be normal, but it lies through its ugly teeth.

function Box3(){
    
    //Yes, I can absolutely pull this crap.
    this.x = 5;
    var x = 6;
    
    this.incrementX = function() {
         x++; //Which variable does x refer to?
        
        //I'll never tell.
    }
}