Why are namespaces considered bad practice in JavaScript?

I was told that namespaces should not be used, as they "pollute" the global area. I wonder what alternatives?

When I want to define utility functions and / or constants, for example. for a website, a simple way would be to identify them by namespaces, so the damage to the global scope is limited to one object.

If namespaces are bad practice, several questions arise:

  • Why is this bad practice?
  • What is the scope of this declaration (web applications / dynamic websites / static websites, etc.)?
  • What are the alternatives?

This question is the result of a discussion that started in a post about the benefits of using extend.js .

+4
source share
4 answers

why is this bad practice?

namespaces are bad because it is an unnecessary concept.

Possible objects with properties and methods. It's also good to have a “module” token that looks like a “namespace,” but the point is that you have one module token for each file that contains all your properties and methods. This is different from the "namespace" because it was created / modified in only one file and was not displayed as a global token.

What is the scope of this declaration (web applications / dynamic websites / static websites, etc.)?

All ECMAScript, never create new global tokens

what alternatives?

, , " ". , / "" , .

, . , , , , javascript.

:

+8

, . , JavaScript, .

, ( ?). ; - , kilo.

" " - , , . window.alert, , ; kilo.alert ( , , ).

+3

, , , , "". Math , . , , , JS . , , core.dialog.alert , .

, . JS script , Alert() AJAX(), . , , . , ( , ).

. window.

+2

JavaScript "namespaces" are really just objects with named properties. In other OO languages ​​(e.g. C ++, C #, etc.) I don't think you need the following:

WITH# -

public static class MyAppName {}
public static class MyArea {}
public static class MySubArea {}

public static class Test {
  public string Property1 { get { return "test"; }}
}

Just so you can

MyAppName.MyArea.MySubArea.Test.Property1;

So basically, since JS doesn't actually support namespaces, people invented a hack to simulate namespaces, which then makes it “healthy” to write things like:

myAppSpace.mySubArea.myObject = blah...
+1
source

All Articles