Functions
JavaScript Lesson 10 2:19 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A function is a job with a name.
函数就是一件有名字的工作。
You write the word function, which tells JavaScript you are defining something rather than running it — nothing in the body happens until somebody calls it.
你先写 function 这个词, 它告诉 JavaScript 你是在定义一个东西,而不是在运行它—— 在有人调用之前,函数体里什么都不会发生。
Then a name, chosen the way you choose a variable name.
接着是名字,取名的规矩和取变量名一样。
Then, in the brackets, the parameters: names for the values the caller will pass in.
然后是括号里的形参:调用者传进来的那些值的名字。
And the body goes in curly braces underneath.
函数体写在下面的花括号里。
Using it looks like this.
用起来是这样的。
You hand it a value — four — which arrives inside as n.
你递给它一个值——4——它在里面就成了 n。
The body runs.
函数体开始执行。
Then return hands one back: eight.
然后 return 交还一个值:8。
And the last step is the one beginners skip: store what comes back, or use it straight away, because the value arrives at the place where the call was written and nowhere else.
最后一步正是初学者容易跳过的:把返回的值存起来,或者立刻用掉, 因为这个值只会到达写下这次调用的地方,别的地方都不会有。
These two look almost identical and behave completely differently.
这两段看起来几乎一样,行为却完全不同。
The first shows it and keeps nothing: the function ends without producing a value, so x is undefined, and adding one to undefined gives NaN — not a number.
第一个只是把结果显示出来,什么也没留下:函数结束时没有产生值, 所以 x 是 undefined,再给 undefined 加 1 得到 NaN——不是一个数字。
The second hands it back: x is eight, and the next line logs nine.
第二个把结果交还回来:x 是 8,下一行打印出 9。
The test is simple — if you cannot store the answer in a variable, the function returned nothing.
判断办法很简单——如果你没法把答案存进一个变量,那这个函数就什么都没返回。
Now the lesson's third task, and it is deliberately the other kind.
现在做课程里的第三道题,它故意是另一种函数。
Greet takes a name and logs a greeting — and it has no return at all.
greet 接收一个名字并打印一句问候——而且它完全没有 return。
That is correct here, because its job IS the logging; there is no answer for a caller to catch.
在这里这是对的,因为它的工作就是打印;没有什么答案需要调用者去接。
One thing to notice: defining it does nothing on its own.
有一点要注意:光是定义它,什么也不会发生。
You have to call it on the line below, with a real name in the brackets, before anything appears.
你必须在下面那一行调用它,括号里给一个真实的名字,才会有东西出现。
Four things to take with you.
带走四点。
One: function, a name, brackets, braces.
第一:function、名字、括号、花括号。
Two: return hands one value back to whoever called it.
第二:return 把一个值交还给调用它的地方。
Three: console dot log shows a value to a human — only return gives a value to the rest of your program.
第三:console.log 是给人看的——只有 return 才能把值交给你程序的其余部分。
Four: defining is not running, so you must call it.
第四:定义不等于运行,所以你必须去调用它。
Now do the three tasks; two return, and the last one does not.
现在去做那三道题;两题要返回,最后一题不用。