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