gpt4 book ai didi

javascript - 如何使用 Javascript 获取作为参数传递的函数名称以用于回调目的

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

我有以下代码示例来获取在参数中传递的函数名称以用于回调目的。

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

最佳答案

您的函数是匿名的;即它们是无名函数表达式。在获得他们的名字之前,您必须先给他们起名字。

var o = {
foo: function bar() {} // named function expression, name is "bar"
};
function getName(fn) {
return fn.name;
}
getName(o.foo); // "bar"

但是,这些函数在您的操作对象中确实有相关的键,但您无法找出对象的哪个>对象某些事情是肯定的,查找匹配的代码将是猜测,因为值不必是唯一的。

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('('));
}
});
}

关于javascript - 如何使用 Javascript 获取作为参数传递的函数名称以用于回调目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22860870/

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