javascript函数简要概述

This is a brief overview of JavaScript functions. I will discuss how functions are defined, as well as explain how functions are called in order to use them. Along with the provided examples, this will give you a better understanding of how to create and use functions in JavaScript.

这是JavaScript函数的简要概述。 我将讨论如何定义函数,并解释如何调用函数以使用它们。 连同提供的示例,这将使您更好地了解如何在JavaScript中创建和使用函数。

Defining Functions

定义功能

There are two ways of defining functions in JavaScript: function declarations and function expressions.

在JavaScript中定义函数的方式有两种: 函数声明函数表达式。

When you declare a function (called a function declaration), you use the function keyword, followed by the name of the function that you give it. Next, comes a list of parameters that the function needs to perform its task (a function can also have no parameters). These parameters are put inside of parentheses and are separated by commas if there are more than one parameter. If the function has no parameters, a set of empty parentheses is used. Finally, the tasks that you want the function to perform are written inside curly braces. A group of statements written inside curly braces (in this case, the tasks that you want the function to perform) is called a code block. In the following example, the function contains only one statement, which is alert("Hello!");. This is an example of a function declaration:

声明函数(称为函数声明 )时,可以使用function关键字,后跟给出的函数的名称。 接下来,是函数执行其任务所需的参数列表(一个函数也可以没有参数)。 这些参数放在括号内,如果有多个参数,则用逗号分隔。 如果函数没有参数,则使用一组空括号。 最后,您希望函数执行的任务写在花括号内。 用花括号括起来的一组语句(在这种情况下,就是您希望函数执行的任务)称为代码块。 在下面的示例中,该函数仅包含一个语句,即alert("Hello!"); 。 这是一个函数声明的示例:

function greeting() {
alert("Hello!");
}

In this simple example, the name of the function that follows the function keyword is greeting. Next, we have parentheses with nothing inside, meaning this function has no parameters. Finally, we have alert("Hello!"); inside the curly braces. This is the task that this function performs. In other words, when this function is called (more on this below), we will get an alert message saying, “Hello!”

在这个简单的示例中,在function关键字之后的函数名称为greeting 。 接下来,我们在括号内没有任何内容,这意味着该函数没有参数。 最后,我们有了alert("Hello!"); 大括号内。 这是此功能执行的任务。 换句话说,当调用此函数时(下文中有更多介绍),我们将收到一条警告消息,说“你好!”。

In this first example, the function does not need any specific information to perform its task — it has no parameters. It just gives us an alert message. However, sometimes a function needs specific information to perform its task. In this case, we need to provide parameters when we declare the function. We give each parameter a name, and in a function, these parameters act like variables. Here is an example of a function with the parameter of name:

在第一个示例中,该函数不需要任何特定信息即可执行其任务-它没有参数。 它只是给我们一个警报消息。 但是,有时某个功能需要特定的信息来执行其任务。 在这种情况下,我们在声明函数时需要提供参数。 我们给每个参数起一个名字,在函数中,这些参数的作用就像变量。 这是带有name参数的函数的示例:

function greeting(name) {
return name;
}

In this function declaration, we have a parameter of name. So, since the function has a parameter, this means that the function needs this information (name) to work. And the task that this function performs is return name;. In other words, the return statement stops the execution of this function and returns the value of name.

在此函数声明中,我们有一个参数name 。 因此,由于该函数具有参数,因此这意味着该函数需要此信息( name )才能起作用。 而该函数执行的任务是return name; 。 换句话说, return语句停止执行此函数并返回name的值。

In this next example, the function has two parameters: name and adjective. This means that this function needs both of these parameters to work. And the task that this function performs is return name + " is " + adjective + ".";. In other words, it will return a string that includes the values of name and adjective.

在下一个示例中,该函数具有两个参数: nameadjective 。 这意味着此功能需要这两个参数才能起作用。 而该函数执行的任务是return name + " is " + adjective + "."; 。 换句话说,它将返回一个包含nameadjective值的字符串。

function greeting(name, adjective) {
return name + " is " + adjective + ".";
}

The second way to define a function is by using a function expression. In a function expression, the name of the function is usually omitted (a function with no name is called an anonymous function). In a function expression, the function is stored in a variable, after which, the variable can be used as a function. This is an example of a function expression:

定义函数的第二种方法是使用函数表达式。 在函数表达式中,通常会省略函数的名称(不带名称的函数称为匿名函数 )。 在函数表达式中,函数存储在变量中,之后,该变量可用作函数。 这是一个函数表达式的示例:

var prices = function(item1, item2) {
return item1 + item2;
}

Here, the function is stored in a variable called prices. This function also has two parameters that it needs to work: item1 and item2. And since this function does not have a name, it’s actually an anonymous function. However, when functions are stored in variables, as is the case here, they do not need to have names, because they are always called using the variable name. Finally, the task that this function performs is return item1 + item2;. So it stops the execution of this function and returns the value of item1 + item2.

在此,该函数存储在名为prices的变量中。 此函数还有两个需要工作的参数: item1item2 。 而且由于该函数没有名称,因此实际上是一个匿名函数。 但是,当函数存储在变量中时(如此处所示),它们不必具有名称,因为它们总是使用变量名来调用。 最后,此函数执行的任务是return item1 + item2; 。 因此,它将停止执行此函数,并返回item1 + item2的值。

调用函数 (Calling Functions)

Now that we looked at the two different ways of creating functions, let’s look at how to actually call, or invoke, these functions. So far, we have seen different examples of functions above. But the way they are written above, they do not actually do anything, meaning that if we actually type the functions exactly as they are written into our text editor and try to run them, nothing will happen. In other words, by writing the following function, for example, we have merely defined the function:

现在,我们介​​绍了创建函数的两种不同方式,让我们看一下如何实际调用调用这些函数。 到目前为止,我们已经看到了上面函数的不同示例。 但是,按照上面的方式编写它们,它们实际上并没有执行任何操作,这意味着,如果我们实际上完全按照将它们写入文本编辑器中的方式键入这些函数并尝试运行它们,则不会发生任何事情。 换句话说,例如,通过编写以下函数,我们仅定义了该函数:

function greeting() {
alert("Hello!");
}

In order to actually use the function (i.e. execute all of the statements between the curly braces), we need to call, or invoke, it. And the way to call a function is to write the name of the function, followed by parentheses. Here, the name of the function is greeting, so the way to call this function is like this:

为了实际使用该函数(即执行花括号之间的所有语句),我们需要调用调用它。 调用函数的方法是编写函数名称,后跟括号。 在这里,该函数的名称为greeting ,因此调用此函数的方式如下:

greeting();

And that’s it. We have the name of the function (greeting), followed by parentheses. And with this line of code, we have called the function, meaning that the function will now perform its task, which in this case means that we will get an alert message saying “Hello!” Putting everything in context, our code looks like this:

就是这样。 我们有函数的名称( greeting ),后跟括号。 在这行代码中,我们调用了该函数,这意味着该函数现在将执行其任务,在这种情况下,这意味着我们将收到一条警告消息,提示您“ Hello!”。 将所有内容放在上下文中,我们的代码如下所示:

function greeting() {
alert("Hello!");
}greeting();

Note that when the function is called here, it is written outside of the curly braces. Another thing to note is that you can call the same function as many times as you want. This means that you can execute the function more than once in your code, depending on your needs.

请注意,在此处调用该函数时,该函数写在花括号之外。 要注意的另一件事是,您可以根据需要多次调用同一函数。 这意味着您可以根据需要在代码中多次执行该功能。

In the next example, our function has one parameter: name. To call a function that has parameters, we need to specify the values that it should use inside of the parentheses. These values are called arguments.

在下一个示例中,我们的函数具有一个参数: name 。 要调用具有参数的函数,我们需要在括号内指定应使用的值。 这些值称为参数。

function greeting(name) {
return name;
}console.log(greeting("Mike"));

In this example, the value that is being specified is the string"Mike" (it is also possible to use a variable as an argument). So here, the function call looks like this: greeting("Mike");. In order to see the result in the console, we use console.log, and then put the function call inside console.log. When this code is run, the following will be logged to the console:

在此示例中,指定的值是字符串"Mike" (也可以使用变量作为参数)。 因此,这里的函数调用如下所示: greeting("Mike"); 。 为了在控制台中查看结果,我们使用console.log ,然后将函数调用放入console.log 。 运行此代码时,以下内容将记录到控制台:

Mike

To call a function with two or more variables, we separate the arguments in the function call using a comma: greeting("Mike", "tall"));. And once again, we use console.log so we can see the result in the console:

要调用带有两个或多个变量的函数,我们使用逗号分隔函数调用中的参数: greeting("Mike", "tall")); 。 再一次,我们使用console.log以便我们可以在控制台中看到结果:

function greeting(name, adjective) {
return name + " is " + adjective + ".";
}console.log(greeting("Mike", "tall"));

When this code is run, the following will be logged to the console:

运行此代码时,以下内容将记录到控制台:

Mike is tall.

So, we have seen examples of how to call function declarations, whether they have no parameters, one parameter, or two or more parameters. Let’s now take a look at how to call function expressions. Remember that in a function expression, the function is stored in a variable. Remember too that in a function expression, the name of the function is usually omitted. So in order to call this type of function, we simply use the name of the variable.

因此,我们已经看到了如何调用函数声明的示例,无论它们没有参数,一个参数还是两个或多个参数。 现在让我们看一下如何调用函数表达式。 请记住,在函数表达式中,函数存储在变量中。 还要记住,在函数表达式中,通常会省略函数的名称。 因此,为了调用这种类型的函数,我们仅使用变量的名称。

var prices = function(item1, item2) {
return item1 + item2;
}console.log(prices(5, 10));

Here, the function is stored in the variable prices. So when we call this function, we call it using the variable prices. This function also has two parameters: item1 and item2. And inside the curly braces is what the function is tasked to do. It will return the sum of item1 and item2. So when we call the function, we need to specify the values of the arguments that should be used inside the parentheses (in this case, 5 and 10). So we call the function by writing prices(5, 10);. But once again, we want to see the result in the console, so we use console.log. And so the following is printed in the console:

在此,该功能存储在可变prices 。 因此,当我们调用此函数时,我们使用变量prices来调用它。 此函数还具有两个参数: item1item2 。 在花括号内是该函数的任务。 它将返回item1item2之和。 因此,当我们调用该函数时,我们需要指定括号内应使用的参数值(在本例中为510 )。 因此我们通过编写prices(5, 10);调用该函数prices(5, 10); 。 但是再次,我们希望在控制台中看到结果,因此我们使用console.log 。 因此,控制台中将显示以下内容:

15

Another way of getting the same result would be to set the function call to a variable, and then to use that variable name inside of console.log to get the result.

获得相同结果的另一种方法是将函数调用设置为变量,然后在console.log使用该变量名来获得结果。

var prices = function(item1, item2) {
return item1 + item2;
}var total = prices(5, 10);console.log(total);

Here, the function call (prices(5, 10)) is set to the variable total. When we do console.log(total), we get the same result in the console:

在这里,函数调用( prices(5, 10) )设置为变量total 。 当我们执行console.log(total) ,我们在控制台中得到了相同的结果:

15

匿名函数 (Anonymous Functions)

As noted above, an anonymous function is a function with no name. Since an anonymous function does not have a name, it cannot be called. An anonymous function is usually not accessible after its initial creation. As stated above, a function that is created as a function expression with no name (an anonymous function) is stored in a variable, and then that variable is used to call it. However, anonymous functions are often used as parameters of other functions, as the following example illustrates.

如上所述,匿名函数是没有名称的函数。 由于匿名函数没有名称,因此无法调用它。 匿名函数最初创建后通常无法访问。 如上所述,将创建为不带名称的函数表达式的函数(匿名函数)存储在变量中,然后使用该变量来调用它。 但是,匿名功能通常用作其他功能的参数,如以下示例所示。

As explained above, we can use functions as often as we need to, simply by calling them anywhere in our code. As anonymous functions are usually not accessible after their initial creation, they are run immediately and are used for code that only needs to run once, most commonly in event handlers and listeners when an event occurs. Consider the following example.

如上所述,我们可以根据需要频繁使用函数,只需在代码中的任意位置调用它们即可。 由于匿名函数在初始创建后通常无法访问,因此它们会立即运行并用于只需要运行一次的代码,最常见的是在事件发生时在事件处理程序和侦听器中运行。 考虑以下示例。

document.getElementById('big-button').addEventListener('click', function() {
alert('Hello!');
}

What happens here, is that when a button with the ID of big-button is clicked, an alert message saying “Hello!” appears in the browser. This happens because of the event listener that has been added here (click). The addEventLister() method can have up to three parameters (event, function, and useCapture). Here, the click event is passed in as the first parameter, and the anonymous function is passed in as the second argument — since this function has no name, it is an anonymous function. As soon as the button is clicked, the function is executed. As you can see, the task that this function performs is alert('Hello!'). Here, it is run immediately and is used only once here within this task. In other words, this function is executed only when this button is clicked.

这里发生的是,当单击ID为big-button的按钮时,显示一条警告消息“ Hello!”。 出现在浏览器中。 发生这种情况是由于已在此处添加了事件侦听器( click )。 addEventLister()方法最多可以具有三个参数( eventfunctionuseCapture )。 在这里, click事件作为第一个参数传递,匿名函数作为第二个参数传递-由于此函数没有名称,因此它是一个匿名函数。 单击该按钮后,该功能即被执行。 如您所见,此函数执行的任务是alert('Hello!') 。 在此,它将立即运行,并且在此任务中仅在此处使用一次。 换句话说,仅当单击此按钮时才执行此功能。

摘要 (Summary)

This article looked at the two different ways that functions are defined in JavaScript (function declarations and function expressions), and looked at how to define functions that have no parameters, one parameter, or two or more parameters. Next, since merely defining a function does not actually execute the function, the section that followed explained how to call a function, so that the function actually runs and performs the task(s) specified within its code block. Lastly, anonymous functions were discussed.

本文探讨了在JavaScript中定义函数的两种不同方式(函数声明和函数表达式),并探讨了如何定义不带参数,一个参数或两个或多个参数的函数。 接下来,由于仅定义一个函数实际上并未执行该函数,因此后面的部分说明了如何调用函数,以便该函数实际运行并执行其代码块中指定的任务。 最后,讨论了匿名函数。

There are still other areas that can be discussed regarding functions, such as scope, closures, hoisting, etc. But the focus here is merely to explain how functions are defined and called in JavaScript.

关于功能,还有其他一些领域可以讨论,例如范围,闭合,提升等。但是这里的重点仅仅是解释如何在JavaScript中定义和调用函数。

  1. Duckett, J. (2014). JavaScript and JQuery: Interactive Front-End Web Development. Wiley.

    Duckett,J.(2014年)。 JavaScript和JQuery:交互式前端Web开发。 威利。

  2. MDN Docs

    MDN文件

  3. W3Schools

    W3学校

翻译自: https://medium.com/weekly-webtips/javascript-functions-a-brief-overview-8afd4f795867

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值