Javascript: protecting global variables

I come from C ++ background, where if you declared a namespace or class, its identifier cannot be overwritten, but in JS I can just create a global variable with the name of the most important namespace in the project and destroy the whole project!

How do you js developers deal with this? Is there any way to fix global variables? If not, how do you manage to work with large projects in JS?

+4
source share
1 answer

mate, in js, you are sure to create a namespace like this:

var mySpace ={

 propertyA: null,
 propertyB: 'ValueB',
 MethodA: function()
{
 console.log('Iam A method');
}
}

then you can call a method like

 mySpace.MethodA();

in practice, it’s good to create one js file per js namespace, it is easy to manage.

+1

Source: https://habr.com/ru/post/1614115/


All Articles