olanchuy
olanchuy

Reputation: 415

create a namespace in javascript

Do you know how to create a name for a constructor object in javascript? I have a fiddle please look at this. http://jsfiddle.net/m8jLoon9/2/

ex.

// you can name the object by using this
function MyConstructorName() {}

// with this one, the name of the objct is the variable
var varConstructorName = function() {};


// MyConstructorName{}
console.log( new MyConstructorName() );

// varConstructorName{}
console.log( new varConstructorName() );

// I have a function that creates an object
// with the name arguments provided
function createANameSpace(nameProvided) {
    // how to create a constructor with the specified name?
    // I want to return an object



    // EDITED, this is wrong, I just want to show what I want on this function
    var TheName = function nameProvided() {};

    // returns an new object, consoling this new object should print out in the console
    // the argument provided
    return new TheName();
}

// create an aobject with the name provided
var ActorObject = createANameSpace('Actor');

// I want the console to print out
// Actor{}
console.log( ActorObject  );

Upvotes: 0

Views: 68

Answers (2)

tengbretson
tengbretson

Reputation: 169

This seems like an abuse of the language, but you can return arbitrarily named objects by doing something like this:

function createANamespace(nameProvided) {
  return {
    constructor: {name: nameProvided}
  };
}

I only tried this on chrome, so ymmv.

Edit: Or, if you really want to abuse the language:

function createANamespace(name) {
  return new Function('return new (function '+ name + '(){} )')
}

Upvotes: 1

L.H
L.H

Reputation: 323

Its actually achieved quite simply as follows

Create it by:

var my_name_space = { first: function(){ alert("im first"); }, second: function(){ alert("im second"); } };

Access it by:

my_name_space.first();

or

my_name_space.second();

It is very similar to storing variables in an object:

var car = {type:"Fiat", model:500, color:"white"};

Except the "Fiat" is another function itself. You could consider the namespace being and object with functions.

Upvotes: 2

Related Questions