javascriptjavascript-objectsjavascript-namespaces

Javascript - Object Notation Script vs Object Oriented Script


I have been working on web applications for very long time. Worked with most experienced technical architects. Everywhere I used javascript in object notation with namespaces.

var web = {};
web.app = {};
web.app.customer = {
    name: 'John',
    getName: function(){
        return 'The name is ' + this.name;
    }
};

document.write(web.app.customer.getName());

But, when I look for any object oriented javascript, we come with function and creating object of it by calling its constructor.

function Customer(name){
    this.name = name;
    this.getName = function(){
        return 'The name is ' + this.name;
    }
}

var cust = new Customer('Bob');
document.write(cust.getName());

I am not sure why architects advised me the former approach(namespace) always. I never used the latter approach, whereas the latter one is object oriented javascript.

  1. Cant we have object oriented javascript with namespace notation(former one)? If so can you create an object of that and inherit them.
  2. Why can't I have private fields in first approach(namespace)? If I declare any field with var, javascript error is thrown.

Solution

  • The only difference between the two approaches is that the former (literal notation) creates one specific object, while the latter defines a constructor function which can be used to create objects. It's the difference between being able to only have one object (asterisk argument about object cloning here), and being able to instantiate many similar objects from the same template ("class").

    Both are equally valid, depending on what you want. Both are equally object oriented.

    Cant we have object oriented javascript with namespace notation(former one)? If so can you create an object of that and inherit them.

    web.app.Customer = function (name) {
       ..
    };
    

    Why can't I have private fields in first approach(namespace)? If I declare any field with var, javascript error is thrown.

    Because "private fields" don't exist in Javascript. You can use the characteristics of closures/variable scoping to emulate something like "private properties". But for that you obviously need a function. With an object literal notation, you don't get that.