Creating classes in Javascript - Prototype method

Javascript is weeeell a script-based language. But over the years it has evolved a lot! So can we develop in an Object Oriented Way using javascript? Of course we can! Here is one (of many) way of creating a class in javascript using the prototype method (beware there is also a javascript framework - like jQuery that has the same name)!

Let's create a person class that has two methods (IsHungry,Eat) and two fields (ring any bells?):

Person = function(fullname) {
    this.fullName = fullname;
    this.foodQuantity = 0;

Person.prototype = {
    eat: function() {
    isHungry: function(){
        return true;

The we can use our class like any other OO language :

var p = new Person(‘John’);
if(p.isHungry()) {;

Although it looks like a class and feels like a class we can’t have private and public members. Everything is public. That means :


is perfectly valid. There is a way of creating classes with true public and private fields but this is something for another post. I also prefer this way despite the public/private flaw.

PS: If there is a way of implementing private fields and methods using the Prototype method please let me know.




    Your example doesn't work.
    $1Prototype like this:
    $ function() {
    $1 this.foodQuantity++;
    $1 alert(this.foodQuantity);
    $1Person.prototype.isHungry: function(){
    $1 return true;



    I meant this:
    $ = function() { this.foodQuantity++; alert(this.foodQuantity); }; Person.prototype.isHungry = function(){ return true; };
    $1(Forgot to replace the colons with equal signs)



    Problem fixed! Thanks for the notice!

Add a Comment (gravatar-enabled)