两种功能的区别? (“函数x"与“变量x =函数") [英] The difference between the two functions? ("function x" vs "var x = function")

查看:72
本文介绍了两种功能的区别? (“函数x"与“变量x =函数")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
JavaScript:var functionName = function(){} vs function functionName(){}

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}

之间有什么区别

function sum(x, y) {
  return x+y;
}

// and 

var sum = function (x, y) {
    return x+y;
}

为什么一个用在另一个上?

Why is one used over the other?

推荐答案

第一个称为命名函数,第二个称为匿名函数.

The first is known as a named function where the second is known as an anonymous function.

主要的实际区别在于何时可以使用求和函数.例如:-

The key practical difference is in when you can use the sum function. For example:-

var z = sum(2, 3);
function sum(x, y) {
    return x+y;
}

z被分配为5,而这是:-

z is assigned 5 whereas this:-

var z = sum(2, 3);
var sum = function(x, y) {
    return x+y;
}

将失败,因为在第一行执行时,尚未将变量sum分配给该函数.

Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.

在开始执行之前,已解析命名函数并将其分配给它们的名称,这就是为什么可以在其定义之前的代码中使用命名函数的原因.

Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.

通过代码分配了功能的变量显然只能在执行超过分配后才能用作功能.

Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.

这篇关于两种功能的区别? (“函数x"与“变量x =函数")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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