Object-Oriented programming in javascript #2

if you don’t know what is Object-Oriented programming in javascript, check the first part of this article.  The idea behind creating a namespace in JavaScript is simple: create one global object, and all variables, methods, and functions become properties of that object. Use of namespaces also reduces the chance of name conflicts in an application, since each application’s objects are properties of an application-defined global object.

Let’s create a global object called MYAPP:

// global namespace
var MYAPP = MYAPP || {};

In the above code sample, we first checked whether MYAPP is already defined (either in the same file or in another file). If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP which will encapsulate methods, functions, variables, and objects.

We can also create sub-namespaces (keep in mind that the global object needs to be defined first):

// sub namespace
MYAPP.event = {};

The following is code syntax for creating a namespace and adding variables, functions, and a method:

// Create container called MYAPP.commonMethod for common method and properties
MYAPP.commonMethod = {
  regExForName: "", // define regex for name validation
  regExForPhone: "", // define regex for phone no validation
  validateName: function(name){
    // Do something with name, you can access regExForName variable
    // using "this.regExForName"
  validatePhoneNo: function(phoneNo){
    // do something with phone number

// Object together with the method declarations
MYAPP.event = {
    addListener: function(el, type, fn) {
    // code stuff
    removeListener: function(el, type, fn) {
    // code stuff
    getEvent: function(e) {
    // code stuff
    // Can add another method and properties

// Syntax for Using addListener method:
MYAPP.event.addListener("yourel", "type", callback);

Standard built-in objects

JavaScript has several objects included in its core, for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.


Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.

I hope you will find this post very useful regarding Object Oriented Programming in Javascript. Let me know if you have any question regarding Javascript in the comment . I will reply to you ASAP.

Have you got a cool idea about Web Application Development ? Contact us Now to get a free consultation on your idea. Alphanso Tech is rated as one of the best Web Application Development Company in India.

Post by Milan Sanathara

I am iOS Application Developer with an aspiration of learning new technology and creating a bright future in Information Technology.

Leave a Reply

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