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:

So you can start using the class like this:

 

8 thoughts on “How to define your own JavaScript class”

  1. 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:

    {syntaxhighlighter brush: javascript}

    var Person = function() {

    this.age = “25”

    this.getASL = function() {

    // stuff here

    }

    }

    {/syntaxhighlighter}

    or

    {syntaxhighlighter brush: javascript}

    function Person() {

    this.age = “25”

    //etc

    }

    Person.prototype.getASL() = function () {

    // stuff here

    }

    {/syntaxhighlighter}

    Its an anal comment but still something nice to know.

  2. and how does one define a function with input? How would one, for instance, define a setAge(var age) function for Person, so we can say

    {syntaxhighlighter brush: javascript}

    var person = new Person();

    person.setAge(23);

    alert(“person’s age: “+person.getAge());

    {/syntaxhighlighter}

  3. Nice post 🙂

    Actually JSON objects are singleton objects by design, not by choice, since they have no constructor. I really like JSON 😀

    So using the JSON you can define a class, while at the same time creating an instance (object) of that class, means that you can have only one single instance of this class at any time, you cannot instantiate more objects of the same class.

    More here:

    http://mahtonu.wordpress.com/2010/04/13/json-style-javascript-object-declaration/

  4. Incredibly beneficial article. I’ve discovered your web site by Google and I am genuinely happy about the information you present with your posts. Anyway keep in the great hard work!

Leave a Reply

Your email address will not be published. Required fields are marked *