wp_localize_script() and JavaScript namespaces

The way wp_localize_script() is supposed to be used is for that 2nd argument to be your namespace. Then you put an array as the 3rd argument for the values:

wp_localize_script(
    'my-script', 
    'namespace_name',
    array(
        'var_name' => $var,
    )
);

Now you can access the variable in the script with namespace_name.var_name.

If you also use the namespace in your script, instead of initialising the object, retrieve the object created by WordPress (or fall back to a new object if it’s missing) and add to it:

var namespace_name = window.namespace_name || {};
namespace_name.new_var="Hello world!";