在javascript中创建一个命名空间

时间:2014-10-24 21:46:18

标签: javascript object constructor namespaces

你知道如何在javascript中为构造函数对象创建名称吗?我有一个小提琴请看这个。 http://jsfiddle.net/m8jLoon9/2/

离。

// 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  );

2 个答案:

答案 0 :(得分:2)

它实际上非常简单地实现如下

通过以下方式创建:

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

通过以下方式访问:

my_name_space.first();

my_name_space.second();

这与在对象中存储变量非常相似:

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

除了“菲亚特”本身是另一个功能。您可以将命名空间视为具有函数的对象。

答案 1 :(得分:1)

这似乎是滥用语言,但您可以通过执行以下操作返回任意命名的对象:

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

我只在chrome上试过这个,所以ymmv。

编辑:或者,如果您真的想滥用该语言:

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