How to define your own JavaScript class

There are several ways to define a class in Javascript. I will be listing my favorite method below (JSON Method). It’s important to note that there are no real classes in JavaScript. Everything is considered an object. So below is our class definition:

<script type="text/javascript">
var Person = {
    age: "25",
    sex: "Male",
    location: "New York",
    getASL: function () {
        return 'Age: ' + this.age + ', Sex: ' + this.sex + ', Location: ' + this.location;
    }
};
</script>

So you can start using the class like this:

<script type="text/javascript">
Person.age = "29";
alert(Person.getASL());
</script>

Tags:

3 Responses to “How to define your own JavaScript class”

  1. Doug

    This was very helpful.

  2. Joseph Montanez

    Actually thats an object. If you ever do new Person(), its ignored and your just copied the object. So what doesn’t work is if try to prototype Person so what every existing object of Person will also be extended with the new function / variable.

    so it should be:
    var Person = function() {
    this.age = “25″
    this.getASL = function() {
    // stuff here
    }
    }
    or
    function Person() {
    this.age = “25″
    //etc
    }
    Person.prototype.getASL() = function () {
    // stuff here
    }

    Its an anal comment but still something nice to know.

  3. Richard

    @Joesph

    Thanks!

Leave a Reply