English 中文(简体)
在对象中声明函数名称,为什么? [重复]
原标题:declare function name in object, Why? [duplicate]
  • 时间:2012-05-23 13:03:28
  •  标签:
  • javascript

正在研究一些js代码性能,并看到这一方法:

window.sample = {

    foo: function foo(a,b){
       // code goes here
    }

    bar: function bar(a,b){
       // code goes here
    }

}

您为什么在“职能”一词之后减速函数名称?

帮助调试的剂量?

是好的还是坏的 还是不必要的?

最佳回答

它们不是为Foo和bar属性指定匿名功能,而是指定指定职能。

它可以有助于调试 : 这唯一不同之处, 据我所知, 就是您可以看到调用堆叠中显示的函数名称, 而不是“ 静音匿名函数 ” 。

问题回答

唯一的理由是,您可以在函数内使用该函数本身而不提及对象:

foo: function foo(a,b){
   return a > 0 ? a + foo(a-1,b) : b;
}

注意在浏览器之间对命名函数字典的这种支持不一致, 所以您应该避免使用它 。

这是 named 函数表达式 。 函数的名称仅在函数本身中作为变量可用。 这对循环有用, 例如 :

var obj = {
    foo: function foo(node) {
        // Do something to node

        var childNode = node.firstChild;
        while (childNode) {
            foo(childNode);
            childNode = childNode.nextSibling;
        }
    }
};

大多数浏览器也通过函数的非标准 name 属性提供函数的名称,该属性有助于在调试或检查堆叠痕迹时识别函数。

IE & lt; 9 执行有缺陷, 所以使用它时需要小心。 详情请见 < a href=" http:// kangax. github. com/ nfe/ " rel= "nofollow" > Juriy Zaytsev 有关该主题的出色文章 < /a > 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.