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