gpt4 book ai didi

javascript - 在 JavaScript 中创建命名空间

转载 作者:行者123 更新时间:2023-11-28 19:32:05 25 4
gpt4 key购买 nike

你知道如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com