Skip to content

Instantly share code, notes, and snippets.

@BillClinton
Last active December 19, 2019 04:27
Show Gist options
  • Save BillClinton/3a4302e1a56c72add34da6341ccf55c7 to your computer and use it in GitHub Desktop.
Save BillClinton/3a4302e1a56c72add34da6341ccf55c7 to your computer and use it in GitHub Desktop.
JS ES5 classes

A Class in JS:

function Animal(){  

    // Private property
    var alive=true;

    // Private method
    function fight(){ //... }   

    // Public method which can access private variables
    this.isAlive = function() { return alive; } 

    // Public property
    this.name = "Joe";
}

// Public method
Animal.prototype.play = function() { alert("Bow wow!"); }

// .. and so on

Now when you create it's object

var obj = new Animal();

You can expect anything of this object as you would from objects in other language. Just the efforts to achieve it, was a bit different. You should also be looking at inheritance in JS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment