Javascript OOP best practices? [closed]

These are just a few quick guidelines I’ve come up with, if anyone else has anything meaningful to add, I’ve set this answer as a community wiki so it should be easy enough for you to edit.

  1. Namespace your objects to ensure they will never conflict with third party JavaScript libraries.
    window['Andrew']['JS'] = {
        addEvent: function(el,evName) {/*Stuff*/},
        Rectangle: function(width,height) {/*Stuff*/}
    };

    So then you would create a rectangle object by using:

    var myRect = new Andrew.JS.Rectangle(14,11);

    And then your code will never interfere with, or be interfered by anybody else’s Rectangle.

  2. Use a consistent naming strategy, specifically:
    • Object names should be capitalized, everything else (variables, functions) should begin with a lower case character i.e.
      var myRect = new Andrew.JS.Rectangle(14,11);
      document.write(myRect.getArea());
    • Ensure everything is meaningful, i.e. verbs for methods, nouns + adjectives for parameters.
  3. Make sure all methods and parameters are relevant to the object they belong to. e.g.

    In this example, the area of the rectangle can be converted to square feet using the method inSquareFeet().

    myRect.getAreaObject().inSquareFeet();

    Make sure inSquareFeet is a method of the object returned by getAreaObject() and not a method of Andrew.JS.Rectangle

  4. Use constructors, or more specifically, try as hard as possible to make sure that an object doesn’t need any further initialization to be used once it has been constructed, so instead of:
    var Person = function()
    {
        this.name = "";
        this.sayHello = function ()
        {
            alert(this.name + " says 'Hello!'");
            return this;
        }
    }
    
    var bob = new Person();
    bob.name = "Bob Poulton";
    bob.sayHello();

    try:

    var Person = function(name)
    {
        this.name = name;
        this.sayHello = function ()
        {
            alert(this.name + " says 'Hello!'");
            return this;
        }
    }
    
    var bob = new Person("Bob Poulton");
    bob.sayHello();

Leave a Comment