【发布时间】:2014-10-24 21:46:18
【问题描述】:
您知道如何在 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 );
【问题讨论】:
-
控制台中的“名称”是内部提供给开发工具的,它不是代码本身可以反映的东西。 function.name 必须来自函数语句。你可以使用 eval() 来构建一个命名函数,就像一个硬编码的函数一样,但是由于这个名字无论如何都没有用,所以不值得。
-
是的,它在 devtools 上,但至少会显示名称。 :)
标签: javascript object constructor namespaces