问题描述
function myfunction(fruit){
alert('我喜欢'+水果+'!');
}
或类似物:
var myfunction = function(水果){
alert('我喜欢'+水果+'!');
};
然而,最近我注意到有些人实际上把函数定义为常量:
const myfunction = fruit =>警报('我喜欢'+水果+'!');
甚至使用关键字 let :
let myfunction = fruit =>警报('我喜欢'+水果+'!');
此时我很困惑。
- 为什么有这么多的定义函数的方法?
- 何时/应该在哪里使用每一个?
- 是否更有效? 我认为这取决于您的需求。例如
这将在你的本地范围内使用 myfunction 名称定义你的函数
function myfunction(fruit){
alert('我喜欢'+ fruit +'!');
}
另一方面,下面的代码将定义一个变量称为 myfunction ,它指向您本地作用域内的通用函数。
var myfunction = function(fruit){
alert('我喜欢'+ fruit +'!');
};
下面的代码将定义一个,目前所有浏览器都不支持。此外, let 语句声明一个块作用域局部变量,可以将其初始化为一个值。因此,在代码块关闭后,您的 myfunction 变量将不会被看到。
let myfunction = fruit =>警报('我喜欢'+水果+'!');
让允许您声明变量在范围上限于使用它的区块,声明或表达。您可以阅读更多内容并在此处查看一些
正如官方文件所言:
const myfunction = fruit =>警报('我喜欢'+水果+'!');
因此,如果您尝试重新分配 myfunction 会失败(默默地)(但在Safari中不会失败)
//这将在Firefox和Chrome中无提示失败
myfunction = fruit =>警报('不!我不喜欢'+水果+'!');
关于让和 const >相似之处MDN引用说明
所以,as ,
阅读更多关于 const
I have always learned that to declare a function in javascript you should do something like:
function myfunction(fruit){ alert('I like ' + fruit + '!'); }
or something like:
var myfunction = function(fruit){ alert('I like ' + fruit + '!'); };
However, most recently, I have noticed that some people actually define functions as constants:
const myfunction = fruit=> alert('I like ' + fruit + '!');
Or even using the keyword let:
let myfunction = fruit=> alert('I like ' + fruit + '!');
At this point I am quite confused.
- Why so many ways of defining functions?
- When/where should I use each one?
- Which way is more efficient?
I think it will depend on your needs. For example
this will define your function with myfunction name on your local scope
function myfunction(fruit){ alert('I like ' + fruit + '!'); }
on the other hand, the code below will define a variable called myfunction that points to an annonimous function inside your local scope.
var myfunction = function(fruit){ alert('I like ' + fruit + '!'); };
while the code below will define an arrow function of ECMA6 that are not supported by all browsers at the current date. Besides, let statement declares a block scope local variable, optionally initializing it to a value. So your myfunction variable won't be seen after the code block is closed.
let myfunction = fruit=> alert('I like ' + fruit + '!');
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. You can read more and see some examples here
As the oficial documentation says:
const myfunction = fruit=> alert('I like ' + fruit + '!');
So if you try to reassign myfunction it will fail (silently) (but does not fail in Safari)
// this will fail silently in Firefox and Chrome myfunction = fruit=> alert('No! I DO NOT like ' + fruit + '!');
About let and const similarities the MDN reference says that
So, as Aurelio de Rosa says,
Read more about const here
这篇关于在Javascript中声明函数的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!