Better JavaScript-User Defined Objects

In my last post I had a look at how we declare namespaces in JavaScript.  In that example I simply declared a function which was then accessible anywhere by simply referencing the correct namespace.  Today I’m going to take a look at creating custom JavaScript objects using the same kind of namespace syntax.

(function( company, undefined ) {
    company.Employee = function(name, salary) {
        this.name = name;
        this.salary = salary;
        this.modifySalary = modifySalary;
    }

    function modifySalary(change) {
        this.salary += change;
        console.log( "Changed the salary for " + this.name );
    }
}( window.company = window.company || {} ));

We want to be able to create instances of the employee object which must be located in the company namespace.  (I already showed in the last post how to extend the namespace – pretty much just use the exact same syntax)  Now we can easily create new instances of the employee object.

var bob = new company.Employee("bob", 5000);
var john = new company.Employee("steve", 4500);

console.log("Name - " + bob.name + ", Salary - " + bob.salary);
console.log("Name - " + john.name + ", Salary - " + john.salary);

john.modifySalary(900);

console.log("Name - " + bob.name + ", Salary - " + bob.salary);
console.log("Name - " + john.name + ", Salary - " + john.salary);

JavaScript Console Output

So now we can create our own objects while keeping the namespaces.  Note the way I created the modifySalary function – as a private function within the namespace.  If I declared it as an inline function we would create function every time a new object instance is created.

Do you have a better way of creating your own JavaScript objects?  If so, I’d love to hear it.

Happy coding.