用javascript创建一个名称空间

create a namespace in javascript

本文关键字:一个 空间 javascript 创建      更新时间:2023-09-26

您知道如何用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  );

它实际上很简单地实现了如下

创建人:

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"};

除了"菲亚特"本身就是另一个功能。您可以考虑名称空间是和具有函数的对象。

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

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

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

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

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