SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Mar 2006
    0 Post(s)
    0 Thread(s)

    JavaScript class creation query

    I have came across 3 different ways of creating a structure or class.

    1. Class as a function way

    // Class Constructor
    function Timer(Source) {

    // Class Properties
    this.timerID = 0;
    this.tStart = null;

    // Class Methods
    this.UpdateTimer = function() {

    // Example
    var timer = new Timer(0);

    2. Class.create & prototype way

    var WindowDelegate = Class.create();
    WindowDelegate.prototype = {
    // Class Constructor
    initialize: function() {
    canClose: function(win) {

    3. Declare as a var way

    var myObserver = {
    variable: null,
    anotherVariable: 33
    stringVariable: 'asdf',
    aFunction: function(a, b) {

    I assume #3 is just a object/structure instance rather than a class definition.

    Has anyone came across #1 way? What are the differences between these 3 ways?
    And what is the proper way to define a class?

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    0 Post(s)
    0 Thread(s)
    Using a function constructor as in your first example allows you to
    enhance the object prototype for objects of the constructor type,
    adding custom properties and methods to every object created as a new constructor().
    To simulate class inheritance you need the constructor, which becomes
    the new prototype for the new variant of the (new) constructor type of object.

    Defining an object with all of its methods and properties as a global variable,
    as your third example illustrates, has a simple, robust syntax, but it is not easily extensible. Sometimes that's what you need.

    The second method has none of the advantages of the other examples,
    but it is more complicated.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts