我有以下代码示例来获取函数名称,该函数名称在参数中传递以用于回调目的。
var operation = {
display : function(fun) {
console.log('operation "'+ fun.toString() +'" performing' );
//here i am getting
/*operation "function () {
console.log('operation "subtraction" performed' ); }" performing
*/
// **instead of entire function i would like to get only method name**
fun.call();
},
addition : function() {
console.log('operation "addition" performed' );
},
subtraction : function() {
console.log('operation "subtraction" performed' );
},
multiplication : function() {
console.log('operation "multiplication" performed' );
}
}
operation.display(operation.subtraction);
//Output should be
// operation "subtraction" performing
// operation "subtraction" performed
operation.display(operation.multiplication);
//Output should be
// operation "multiplication" performing
// operation "multiplication" performed
operation.display(operation.addition);
//Output should be
// operation "addition" performing
// operation "addition" performed
答案 0 :(得分:2)
你的职能是匿名的;即它们是无名函数表达式。在获得他们的名字之前,你必须给他们起名字。
var o = {
foo: function bar() {} // named function expression, name is "bar"
};
function getName(fn) {
return fn.name;
}
getName(o.foo); // "bar"
但是,这些功能在您的operation
对象中确实有相关的密钥,但您无法找到对象<的密钥某些东西是肯定的,找到匹配的代码是猜测,因为价值观不一定是唯一的。
function guessKey(val, obj) {
var key;
for (key in obj)
if (obj[key] === val)
return key;
return null;
}
guessKey(o.foo, o); // "foo"
Function.prototype.name
为IE9 +填充(也许是8;不确定)
if (Function.prototype.name === undefined) { // may be "" so can't use !
Object.defineProperty(Function.prototype, "name", {
get: function () {
var s = Function.prototype.toString.call(this);
return s.slice(9, s.indexOf('('));
}
});
}
答案 1 :(得分:1)
函数对象包含返回方法名称的“name”属性
<强>更新强> AS IE没有实现函数的name属性使用RegEx;)这个小函数可以帮助你:
function getFnName(fn) {
var f = typeof fn == 'function';
var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/));
return (!f && 'not a function') || (s && s[1] || 'anonymous');
}