Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructors inside a namespace

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);
like image 399
Joe Avatar asked Jun 10 '12 16:06

Joe


People also ask

What is inside constructor in C++?

What is a Constructor in C++? A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created.

What are the rules for namespace in C++?

Namespace declarations appear only at global scope. Namespace declarations can be nested within another namespace. Namespace declarations don't have access specifiers (Public or Private). No need to give a semicolon after the closing brace of the definition of namespace.

What is a namespace in C++?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

How do you declare namespace?

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.


1 Answers

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);
like image 184
Ja͢ck Avatar answered Oct 12 '22 09:10

Ja͢ck