javascript - 在 JavaScript 中创建命名空间

标签 javascript object constructor namespaces

你知道如何在 JavaScript 中为构造函数对象创建名称吗?我有一把 fiddle ,请看看这个。 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"};

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

关于javascript - 在 JavaScript 中创建命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26556762/

相关文章:

c++ - vector 构造函数中的函数匹配

javascript - 在单个 WebForm 中拥有多个 Google Maps API

javascript - 应用于导航栏的台式机和笔记本电脑的屏幕宽度

C#:打印对象的所有属性

java - 同一对象的重量级和轻量级版本

javascript - React - 如何循环和更新对象模型中的值?

javascript - 我需要一个 html 音频元素来使用网络音频 api 播放歌曲吗

javascript - 如何创建包含可通过侧边栏切换的多页数据的页面?

javascript - 创建包含或不包含 `new` 的数组

C++ VS2013 : overwriting default constructor not working