什么时候使用匿名JavaScript函数? [英] When to use anonymous JavaScript functions?

查看:97
本文介绍了什么时候使用匿名JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解何时使用匿名JavaScript函数.

I'm trying to understand when to use anonymous JavaScript functions.

功能之间的状态差异?说明何时使用它们.

State differences between the functions? Explain when you would use each.

var test1 = function(){
    $("<div />").html("test1").appendTo(body)
};

function test2() {
    $("<div />").html("test2").appendTo(body)
}

我认为答案是,一个使用匿名函数,另一个不替换空的div元素.看起来正确吗?

I think the answer is that one uses anonymous function and the other doesn't to replace an empty div element. Does that seem right?

推荐答案

在您的示例中,它的作用并不大.唯一的区别是,使用function foo() { }声明的函数可随时在同一范围 中的任何位置访问,而使用var foo = function () { }声明的函数只能在 之后的代码中访问.作业已经执行了吗?

In your example it really doesn't make a huge difference. The only difference is that functions declared using function foo() { } are accessible anywhere within the same scope at any time, while functions declared using var foo = function () { } are only accessible after the code that does the assignment has run.

foo(); // ok
function foo() { ... };

bar(); // error, bar is not a function
var bar = function () { ... };
bar(); // ok

通常在不需要命名函数或构造对象的情况下使用匿名函数:

You usually use anonymous functions in cases where you don't need a named function, or where you're constructing objects:

arr.sort(function (a, b) { return a - b; });  // anonymous callback function

function MyObject() {
    this.foo = function () { ... }  // object constructor
}

这篇关于什么时候使用匿名JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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