我认为这取决于您的需求。例如
这将定义你的函数myfunction
您本地范围内的名称
function myfunction(fruit){
alert('I like ' + fruit + '!');
}
另一方面,下面的代码将定义一个variable called myfunction
它指向本地范围内的匿名函数。
var myfunction = function(fruit){
alert('I like ' + fruit + '!');
};
而下面的代码将定义一个ECMA6的箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions目前并非所有浏览器都支持。除了,let
语句声明一个块作用域局部变量,可以选择将其初始化为一个值。所以你的myfunction
代码块关闭后将看不到变量。
let myfunction = fruit=> alert('I like ' + fruit + '!');
let
允许您声明范围仅限于使用它的块、语句或表达式的变量。您可以阅读更多内容并查看一些例子在这里 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
正如官方文档所说:
const 声明创建对值的只读引用。它
并不意味着它所持有的值是不可变的,只是变量
标识符不能被重新分配。
const myfunction = fruit=> alert('I like ' + fruit + '!');
所以如果你尝试重新分配myfunction
它会失败(无提示)(但在 Safari 中不会失败)
// this will fail silently in Firefox and Chrome
myfunction = fruit=> alert('No! I DO NOT like ' + fruit + '!');
About let
and const
MDN 参考文献说的相似之处
常量是块作用域的,很像使用 let 定义的变量
陈述。常量的值不能通过以下方式改变
重新分配,并且不能重新声明。
So, as 奥雷利奥·德·罗莎 说 http://www.sitepoint.com/preparing-ecmascript-6-let-const/,
常量与使用 let 声明的变量共享一个功能
它们是块作用域而不是函数作用域
阅读更多关于const
here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const