最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - constructors inside a namespace - Stack Overflow

programmeradmin3浏览0评论

I have read that creating a namespace for JavaScript projects helps to reduce conflicts with other libraries. I have some code with a lot of different types of objects for which I have defined constructor functions. Is it good practice to put these inside the namespace as well?

For example:

var shapes = {
    Rectangle: function(w, h) {
        this.width = w;
        this.height = h;
    }
};

which can be called via:

var square = new shapes.Rectangle(10,10);

I have read that creating a namespace for JavaScript projects helps to reduce conflicts with other libraries. I have some code with a lot of different types of objects for which I have defined constructor functions. Is it good practice to put these inside the namespace as well?

For example:

var shapes = {
    Rectangle: function(w, h) {
        this.width = w;
        this.height = h;
    }
};

which can be called via:

var square = new shapes.Rectangle(10,10);
Share Improve this question edited Jun 10, 2012 at 16:51 Filburt 18.1k12 gold badges81 silver badges138 bronze badges asked Jun 10, 2012 at 16:28 JoeJoe 4,93010 gold badges65 silver badges85 bronze badges 1
  • Your constructor, which is a function, becomes a function expression instead of a function declaration if you assign it to an object property in a "namespace" instead of simply writing function Rectangle(w, h) {}. This has has slight differences: developer.mozilla.org/de/docs/Web/JavaScript/Reference/… Other than that, it doesn't pollute the global namespace, which is a good thing, as others have pointed out. – caw Commented Nov 13, 2017 at 2:38
Add a comment  | 

5 Answers 5

Reset to default 5

This is generally a good idea; additionally, if your objects require a set of shared functions that should not be exposed you can wrap them all inside a closure, like a module:

var shapes = (function() {
  // private variables
  var foo = 0;

  // private function
  function get_area(w, h)
  {
    return w * h;
  }

  return {
    Rectangle: function(w, h) {
      this.width = w;
      this.height = h;
      // call private function to determine area (contrived example)
      this.area = get_area(w, h);
    }
  }
}());

var s = new shapes.Rectangle(100, 5);

This namespacing is called the "Singleton pattern" and it's one of the main patterns reccomended by the famous "Gang of Four" design patterns book.

From the great (and free) book Learning JavaScript Design Patterns:

Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.The Singleton pattern is thus known because it restricts instantiation of a class to a single object.

In JavaScript, singletons serve as a namespace provider which isolate implementation code from the global namespace so as to provide a single point of access for functions.

They can take on a number of different forms, but in its most basic, a Singleton could be implemented as an object literal grouped together with its related functions and properties...

So yes, it's a well used concept in many programming languages and a great for preventing global namespace object collisions in JavaScript.

See also: Simplest/Cleanest way to implement singleton in JavaScript?

Yes. You should pollute the global namespace the least possible

Yeah, that's a good idea, because you avoid the hassle and confusing caused by polluting the global namespace. Although I personally would change shapes to shape, so you could then have a shape.Rectangle, which makes a little more sense to me (after all, a Rectangle is only one object).

Besides not polluting the namespace, it also enables you to do type family checking:

function doSomethingTo(shape) {
  var shapeName, validArg;

  for (shapeName in shapes) {
    validArg = validArg || shape instanceof shapes[shapeName];
  }

  if ( !validArg ) throw "Argument is not a shape.";
}
发布评论

评论列表(0)

  1. 暂无评论