获取被分配给variables函数的名称

我试图返回一个函数分配给variables的名称。

我已经在下面包含了一个例子。 最终的结果是我想modelPerson.title()返回variables名称title

例如,我有以下代码:

定义一些基本模型types

 var types = { string: function() { return function() { return "I want this to return 'title'"; } } }; 

使用模型types

 var modelPerson = { title: types.string(), firstName: types.string(), surname: types.string(), position: types.string() }; 

试图返回标题

 console.log(modelPerson.title()); 

对不起,如果有点不清楚。 如果有帮助,我已经包含了一个JSFiddle: http : //jsfiddle.net/4f6VE/

谢谢你提供的所有帮助

这实际上是可能的,但涉及一些V8特定的东西:

 var types = { string: function() { return function() { var obj = {}; var prepare = Error.prepareStackTrace; Error.prepareStackTrace = function (_, stack) { return stack } Error.captureStackTrace(obj) var method = obj.stack[0].getMethodName(); Error.prepareStackTrace = prepare; return method; } } }; var modelPerson = { title: types.string(), firstName: types.string(), surname: types.string(), position: types.string() }; console.log(modelPerson.title()); console.log(modelPerson.firstName()); 

但你可能应该使用一些不那么疯狂的东西

我真的不知道这是为了什么,但是

 var modelPerson = { title : function title(){ return arguments.callee.name; }, firstName : function firstName(){ return arguments.callee.name; }, surname : function surname(){ return arguments.callee.name; }, position : function position(){ return arguments.callee.name; }, } 

应该做你说的话。

编辑

Banzaaai〜!

 var types = { string: function(){ eval('var x = function '+arguments.callee.caller.name+'(){var x = function(){return arguments.callee.caller.name;}; return x();}'); return x(); } }; var modelPerson = { title: function title(){ return types.string(); }, firstName: function firstName(){ return types.string(); }, surname: function surname(){ return types.string(); }, position: function position(){ return types.string(); } }; 

SRSLY THOUGH

 var types = { string: function(x){ return function(){ return x; } } }; var modelPerson = { title: types.string('title'), firstName: types.string('firstName'), surname: types.string('surname'), position: types.string('position') }; 

我试图返回一个函数分配给variables的名称

你不能,不可靠。 一些variables或属性可以引用同一个对象,并且一些对象不会被分配给一个variables(例如不带名称的函数expression式立即被调用)。

最终的结果是我想modelPerson.title()返回variables名称标题。

然后使用这样的东西:

 function define(obj, name) { obj[name] = function() { return name; }; } var modelPerson = {}; define(modelPerson, "title"); define(modelPerson, "firstName"); define(modelPerson, "surname"); define(modelPerson, "position"); // … - a loop maybe? 

 > console.log(modelPerson.title()); "title" 

这里是一个可以在严格模式下工作的方法(没有弃用arguments.callee或私有arguments.callee.caller属性),使用你的代码时使用最小的重新分解和没有硬编码的名字:

 var types={ string: function types(){ return function me() { for(var it in this){ if(me==this[it]) return it; } }; } }; var modelPerson = { title: types.string(), firstName: types.string(), surname: types.string(), position: types.string() }; alert( modelPerson.title() ); // shows: "title" alert( modelPerson.surname() ); // shows: "surname"