JavaScript Essentials:功能很有趣(和VIP)-如果您理解它们

by Zell Liew

由Zell Liew

JavaScript Essentials:功能很有趣(和VIP)-如果您理解它们 (JavaScript Essentials: functions are fun (and VIP) — if you understand them)

Imagine you live in a village without tap water. To get water, you need to take an empty bucket, head to the well in the middle of the village, draw water from the well, and head back home.

想象一下,您住在一个没有自来水的村庄。 要获取水,您需要拿空的水桶,直奔村庄中间的水井,从水井中抽水,然后回家。

You need to draw water from this well multiple times a day. It’s a hassle to say “I’m going to take an empty bucket, go to the well, draw water and bring it back home” every time you explain what you’re doing.

您每天需要多次从这口井中抽水。 每当您解释自己在做什么时,都会说“我要去一个空桶,去井里,抽水,然后把水带回家”,这很麻烦。

To shorten it, you can say you’re going to “draw water.”

为了缩短时间,您可以说要“汲水”。

And, my friend, you’ve created a function.

而且,我的朋友,您已经创建了一个函数。

宣告功能 (Declaring functions)

A function is a block of code that executes tasks in a specific order, like take empty bucket, go to well, draw water, head back home.

函数是按特定顺序执行任务的代码块,例如带空桶,走井,抽水,回家。

It can be defined with the following syntax:

可以使用以下语法进行定义:

function functionName (parameters) {   // Do stuff here }

function is a keyword that tells JavaScript you’re defining a function.

function是一个关键字,它告诉JavaScript您正在定义一个函数。

functionName is the name of the function. In the example given above, the function name could be drawWater.

functionNamefunctionName的名称。 在上面给出的示例中,函数名称可以是drawWater

The name of the function can be anything, as long as it follows the same rules as declaring variables. In other words, it needs to follow these rules:

函数的名称可以是任何东西,只要它遵循与声明变量相同的规则即可。 换句话说,它需要遵循以下规则:

  1. It must be one word

    必须是一个字
  2. It must consist only of letters, numbers, or underscores (0–9, a-z, A-Z, _)

    它只能包含字母,数字或下划线(0–9,az,AZ, _ )

  3. It cannot begin with a number

    它不能以数字开头
  4. It cannot be any of these reserved keywords

    不能是这些保留关键字中的任何一个

parameters is optional. It is a comma-separated list of variables you wish to declare for your function. They can be assigned values when you use the function.

parameters是可选的。 这是您希望为函数声明的变量的逗号分隔列表。 使用功能时可以为它们分配值。

使用功能 (Using functions)

Once you’ve declared your function, you can use (or invoke, or call, or execute) it by writing the name of the function, followed by parenthesis ().

声明函数后,可以通过编写函数名称,然后加上括号()来使用(或调用调用执行 )它。

Here’s an example where a sayHello function is declared and used.

这是一个声明并使用sayHello函数的示例。

// Declaring a function
function sayHello () {  console.log('Hello world!')}
// using a functionsayHello()

压痕 (The indentation)

Code within a block (anything within curly braces {}) should be indented to the right. This is an important practice that helps you make code easier to read. It allows you to tell at a glance that console.log('Hello world') is part of sayHello.

块中的代码(大括号{}任何代码)应在右边缩进。 这是重要的实践,可帮助您使代码更易于阅读。 它使您一眼便知道console.log('Hello world')sayHello一部分。

function sayHello () {     // This console.log statement is a part of sayHello       console.log('Hello world!') }

You can choose to indent with two spaces or with a tab key. Some people prefer spaces, others prefer tab. Both are fine, as long as you keep it consistent.

您可以选择缩进两个空格或使用Tab键。 有些人喜欢空格,另一些人喜欢制表符。 两者都很好,只要您保持一致即可。

参量 (Parameters)

Most functions take in parameters. It is a comma-separated list of variables you wish to declare for your function.

大多数功能都带有参数。 这是您希望为函数声明的变量逗号分隔列表

You can have any number of parameters.

您可以具有任意数量的参数。

function functionName(param1, param2, param3) {   // Do stuff here }

To assign values to your parameters, you pass in values (called arguments) by writing them as comma-separated values in the parentheses.

要为参数分配值,请传入值(称为参数),方法是在括号中将它们写为逗号分隔的值。

The first argument would be assigned to the first parameter, the second argument to the second parameter, and so on.

第一个参数将分配给第一个参数,第二个参数将分配给第二个参数,依此类推。

functionName('arg1', 'arg2')

Let’s make it clearer with an example.

让我们通过一个示例使其更加清晰。

Let’s say you wish to write a function called sayName that logs the firstName and lastName of a person. The function looks like this:

假设您希望编写一个名为sayName的函数来记录一个人的firstName和lastName。 该函数如下所示:

function sayName(firstName, lastName) {   console.log('firstName is ' + firstName)   console.log('lastName is ' + lastName) }

Zell is my first name, Liew is my last name. To get the function to work correctly, I pass my Zell, as the first argument, and Liew as the second argument:

Zell是我的名字,Liew是我的名字。 为了使函数正常工作,我将Zell作为第一个参数,并将Liew作为第二个参数:

sayName('Zell', 'Liew') // firstName is Zell // lastName is Liew

If you declared a parameter, but did not pass an argument to it, your parameter would be undefined.

如果您声明了一个参数,但未将参数传递给它,则您的参数将是undefined

sayName() // firstName is undefined // lastName is undefined

退货声明 (The return statement)

Functions can have a return statement that consists of the return keyword and a value:

函数可以具有一个由return关键字和一个值组成的return语句:

function functionName () {   return 'some-value' }

When JavaScript sees this return statement, it stops executing the rest of the function and “returns” (passes the value back to the function call).

当JavaScript看到此return语句时,它将停止执行该函数的其余部分并“返回”(将值传递回函数调用)。

function get2 () {   return 2   console.log('blah') // This is not executed }
const results = get2() console.log(results) // 2 // Note: You would not see 'blah' in the console

If the return value is an expression, JavaScript evaluates the expression before returning the value.

如果返回值是一个表达式,则JavaScript在返回值之前先评估该表达式。

Remember, Javascript can only pass around primitives (like String, Numbers, Booleans) and objects (like functions, arrays and objects) as values. Anything else needs to be evaluated.

请记住, JavaScript只能将基元 (如字符串,数字,布尔值) 和对象 (如函数,数组和对象)作为值传递其他需要评估

功能流程 (Flow of a function)

Functions can be hard for beginners to understand. To make sure you understand functions completely, let’s go through what happens when you declare and use a function again. This time, we’ll take things one step at a time.

对于初学者来说,功能可能很难理解。 为了确保您完全理解函数,让我们回顾一下在声明并再次使用函数时会发生的情况。 这次,我们将一步一步走。

Here’s the code we’re dissecting:

这是我们要分析的代码:

function add2 (num) {   return num + 2 }
const number = add2(8) console.log(number) // 10

First of all, you need to declare a function before you can use it. In the first line, JavaScript sees the function keyword and knows the function is called add2.

首先,您需要先声明一个函数,然后才能使用它。 在第一行中,JavaScript看到function关键字,并且知道该函数称为add2

It skips over the code in the function at this point because the function is not used yet.

由于此时尚未使用该功能,因此它会跳过该功能中的代码。

Next, JavaScript sees you’re declaring a variable called number, and assigning it as the result of add2(8).

接下来,JavaScript看到您在声明一个名为number的变量,并将其分配为add2(8)的结果。

Since the right hand side (RHS) is a function call (an expression), JavaScript needs to evaluate the value of add2(8) before it can assign it to the number variable. Here, it sets the parameter num to 8, since you passed in 8 as the argument when you call add2(8).

由于右侧(RHS)是函数调用(表达式),因此JavaScript需要先评估add2(8)的值,然后才能将其分配给number变量。 在这里,它将参数num8 ,因为在调用add2(8)时传入8作为参数。

In the add2 function, JavaScript sees a return statement that says num + 2. This is an expression, so it needs to evaluate it before moving on. Since num is 8, num + 2 must be 10.

add2函数中,JavaScript看到一个返回语句num + 2 。 这是一个表达式,因此在继续之前需要对其进行评估。 由于num为8, num + 2必须为10。

Once num + 2 is evaluated, JavaScript returns the value to the function call. It replaces the function call with the returned value. So, add2(8) becomes 10.

评估num + 2 ,JavaScript会将值返回给函数调用。 它将函数调用替换为返回的值。 因此, add2(8)变为10。

Finally, once the RHS is evaluated, JavaScript creates the variable, number and assigns the value 10 to it.

最后,一旦评估了RHS,JavaScript将创建变量, number并为其分配值10。

That’s how you read the flow of a function.

这就是您阅读功能流程的方式。

吊装 (Hoisting)

When functions are declared with a function declaration (what you learned above), they are hoisted to the top of your scope. This means the following two sets of code are exactly the same.

当使用函数声明声明函数时(您在上面学到的东西),它们会被提升到您的作用域的顶部。 这意味着以下两组代码完全相同。

function sayHello () {   console.log('Hello world!') } sayHello()
// This is automatically converted to the above code sayHello() function sayHello () {   console.log('Hello world!') }

Function hoisting gets confusing because JavaScript changes the order of your code. I highly recommend you declare your functions before you use them. Don’t rely on hoisting.

因为JavaScript更改了代码顺序,所以函数提升变得令人困惑。 我强烈建议您在使用函数之前先声明它们。 不要依靠吊装。

用函数表达式声明函数 (Declaring functions with function expressions)

A second way to declare functions is with a function expression. Here, you declare a variable, then assign a function without a name (an anonymous function) to it.

声明函数的第二种方法是使用函数表达式。 在这里,您声明一个变量,然后为其分配一个没有名称的函数(匿名函数)。

const sayHello = function () {   console.log('This is declared with a function expression!') }

Note that functions declared with function expressions are not automatically hoisted to the top of your scope.

请注意,用函数表达式声明的函数不会自动提升到作用域的顶部。

sayHello () // Error, sayHello is not defined const sayHello = function () {   console.log('this is a function!') }

At this point, you may wonder if function expressions are important. That’s a common question to have. Why would you use function expressions if you can declare functions with the function declaration syntax?

此时,您可能想知道函数表达式是否重要。 这是一个常见的问题。 如果可以使用函数声明语法声明函数,为什么还要使用函数表达式?

They are important. You’ll learn why when you learn to declare object methods and arrow functions.

它们很重要。 您将了解为什么要学习声明对象方法和箭头函数的原因

结语 (Wrapping up)

A function is a block of code that executes tasks in a specific order, like take empty bucket, go to well, draw water, head back home.

函数是按特定顺序执行任务的代码块,例如带空桶,走井,抽水,回家。

You call functions by adding a () to the end of the function name. When you do so, you can add additional values as arguments to the function.

您可以通过在函数名称的末尾添加()来调用函数。 这样做时,可以将其他值添加为函数的参数。

Each function can have a return statement that “returns” a value to the function call.

每个函数可以具有一个return语句,该语句“返回”一个值给函数调用。

As much as possible, don’t rely on hoisting when you write functions. Always declare them upfront before you use them.

编写函数时,请尽可能不要依赖提升。 使用它们之前,请务必先声明它们。

This article is a sample lesson from Learn JavaScript — a course that helps you learn JavaScript to real, practical components from scratch. You’ll love Learn JavaScript if you found this article helpful. If you loved this article, I invite you to find out more about Learn JavaScript.

本文是学习JavaScript的示例课程,该课程可帮助您从头开始学习JavaScript到实际的实用组件。 如果发现这篇文章对您有帮助,那么您会喜欢Learn JavaScript。 如果您喜欢这篇文章,我邀请您查找有关Learn JavaScript的更多信息

(Oh, by the way, if you liked this article, I’d appreciate it if you could share it. ?)

(哦,顺便说一句,如果您喜欢这篇文章,如果可以分享的话 ,不胜感激。)

Originally published at zellwk.com.

最初在zellwk.com上发布。

翻译自: https://www.freecodecamp.org/news/javascript-essentials-functions-are-fun-and-vip-if-you-understand-them-29da2d4c9641/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值