找出函数是匿名的还是在对象中定义的 [英] Find out if function is anonymous or is defined in a object

查看:96
本文介绍了找出函数是匿名的还是在对象中定义的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用JavaScript编写辅助方法。如果一个函数或一个函数的引用发送它,它应该采取不同的行为。

I'm trying to write a helper method in JavaScript. It should act differently if one sends in a function or an reference to a function.

我想这样使用它:

helper('div', function () { return false; })
helper('div', obj.fn)

我无法弄清楚的是:如何在辅助函数里面说明两者之间的区别?

What I can't figure out is: how to inside the helper function tell the difference between the two?

我认为这是因为JavaScript在发送之前首先评估了obj.fn.
我找到的唯一解决方法是将obj.fn作为obj发送, ie

I think it's due to that JavaScript first evaluates the obj.fn before it sends it in. The only workaround I found is to send the obj.fn as an obj, i.e.

helper('div', { fn: obj.fn })

然后我可以用typeof告诉两者之间的区别。但我真的很喜欢在没有额外对象声明的情况下制作它。

Then I can tell the difference between the two with typeof. But I really like some way to make it without the extra object declaration.

推荐答案

你可以使用 toString ()以确定函数是否是匿名的,假设它被声明为命名函数而不是分配给变量的未命名函数:

You can use toString() to find out if the function is anonymous assuming it is declared as a named function and not an unnamed function assigned to a variable:

function jim () { var h = "hello"; }
function jeff(func) 
{ 
    var fName;
    var inFunc = func.toString();
    var rExp   = /^function ([^\s]+) \(\)/;
    if (fName = inFunc.match(rExp))
       fName = fName[1];

    alert(fName);
}

如果有的话,会给你这个函数的名称。

Will give you the name of the function if any.

jeff(function () { blah(); }); // alert: null;
jeff(function joe () { blah(); }); // alert: "joe";
jeff(jack); // "jack" if jack is function jack () { }, null if jack = function() {} 

我之前的编辑提到了一个IE怪癖,它在其他浏览器中不存在,并且从版本9开始在IE中不再有效。但是,您仍然可以使用命名函数表达式将命名函数指定为对象属性:

My previous edit referred to an IE quirk that didn't exist in other browsers and is no longer valid in IE as of version 9. However, you can still assign named functions as object properties using a named function expression:

var obj = {
    fn: function namedFunction () { }
};

这适用于所有浏览器,但IE 8及更低版本不符合说明函数只能在其自己的块中使用此名称。

This works in all browsers, but IE 8 and lower don't adhere to the specification which says the function is only available by this name inside its own block.

这篇关于找出函数是匿名的还是在对象中定义的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆