Functions

JavaScript Functions (Javascript代码函数)

Like every programming language, JavaScript also supports the use of functions. JavaScript functions are the main blocks of code designed to perform a particular task. Functions allow the code to be called many times without repetition. (与所有编程语言一样, JavaScript也支持函数的使用。 JavaScript函数是用于执行特定任务的主要代码块。 函数允许在不重复的情况下多次调用代码。)

Function Declaration

Function Declaration (子函数声明 。)

We can create functions in JavaScript using a function declaration that looks like this:

function show() {
 console.log('Welcome to w3cdoc!');
}
show();

As you see in the example the function keyword goes first, followed by the name of the function, then we put a list of parameters between the parentheses and finally we place the code of the function between curly braces . (正如您在示例中看到的那样, function关键字先后跟随函数的名称,然后我们在括号之间放置一个参数列表,最后我们将函数的代码放在大括号之间。)

Beautified JavaScript:

Beautified JavaScript:

function name(parameters) {
 //body...
}

We can call our new function by its name: show() which executes the code of the function. As a result, we see the message two times:

function show() {
 console.log('Welcome to w3cdoc!');
}
show();
show();

This example shows one of the main purposes of functions: to avoid code duplication. If we want to change the message, we just need to modify the code in the function which outputs it.

Local variables

Local variables (局部变量)

A variable declared inside a JavaScript function is only visible inside that function. It can only be accessed from within the function. (在JavaScript函数中声明的变量仅在该函数中可见。只能从函数内部访问它。)

Example of the local variable:

function show() {
 let localVar = "Welcome to w3cdoc!"; //it’s a local variable
 console.log(localVar);
}
show(); // Welcome to w3cdoc!
console.log(localVar); // <-- Error! The variable is local to the function

Outer variables

Outer variables (外部变量)

A function can also evaluate an outer variable. (函数还可以计算外部变量。)

Example of the outer variable:

let siteName = 'w3cdoc';
function show() {
 let variable = 'Welcome to ' + siteName;
 console.log(variable);
}
show(); // Welcome to w3cdoc

We use an outer variable only if there is no local one. If some same-named variable is declared inside the function then outer one is ignored. (只有在没有本地变量时,我们才使用外部变量。如果在函数内声明了一些同名变量,则忽略外部变量。)

Example of the function that uses the local variable:

let siteName = 'newSite'; // it’s a outer variable
function show() {
 let siteName = "w3cdoc"; // it’s a local variable
 let message = 'Welcome to ' + siteName; 
 console.log(message);  //Welcome to w3cdoc
}  // the function created and used its own siteName
show();
console.log(siteName);  //newSite,the function didn’t access the outer variable

We declare global variables outside of any function, they are visible from any function. (>我们在任何函数之外声明全局变量,它们在任何函数中都是可见的。)

Modern code has few or no globals, that is why it is better to minimize the use of global variables. (现代代码很少或没有全局变量,这就是为什么最好尽量减少使用全局变量。)

Modern code has few or no globals, that is why it is better to minimize the use of global variables. (>现代代码很少或没有全局变量,因此最好尽量减少使用全局变量。)

Parameters

Parameters (参数)

We can proceed with random data to functions using parameters. In this example, the function has two parameters: arg1 and arg2:

function show(arg1, arg2) { // arguments: arg1, ag2
 console.log(arg1 + ' to ' + arg2);
}
show('Welcome', 'w3cdoc!'); // Welcome to w3cdoc! (*)

The function uses () when the given values are copied to local variables arg1 and arg2. (当给定值复制到局部变量arg1和arg2时,函数使用()。)

In this example we have a variable arg1 and proceed it to the function. Note that the function changes arg1, and the change is not seen outside, as a function always gets a copy of the value:

function sum(arg1, arg2) {
 arg1 = arg1++; // change "arg1" 
 let sum = arg1 + arg2;
 console.log(sum);
}
let arg1 = 2;
sum(arg1, 3); // result: 5
console.log(arg1); // 2

The value of “arg1” is the same, the function modified a local copy. (“arg1”的值相同,函数修改了一个本地副本。)

Default values

Default values (默认值)

Parameters of functions default to undefined if a parameter is not defined. But sometimes it might be useful to set a different default value. (如果未定义参数,则函数的参数默认为undefined。但有时设置不同的默认值可能会有所帮助。)

function show(arg1, arg2) { // arguments: arg1, ag2
 console.log(arg1 + ' to ' + arg2);
}

show("Welcome", "w3cdoc");

For example we can call the aforementioned function show(arg1, arg2) with a single argument:

show("w3cdoc"); // undefined to w3cdoc

That is not an error. This kind of a call would output “undefined to w3cdoc”, but as there is no text it is supposed that text === undefined. (这不是一个错误。这种调用将输出“undefined to w3cdoc” ,但由于没有文本,因此应为text = = = undefined。)

If we want to use a “default” in this case, we can specify it after =:

function show(arg1, arg2 = "w3cdoc!!") {
 console.log(arg1 + " to " + arg2);
}
show("Welcome"); // Welcome to w3cdoc!!

So if the text parameter is not passed, it will get the value “w3cdoc!!”, which is a string in this case, but it can be a more complex expression. That expression is only evaluated and assigned if the parameter is missing and this is also possible:

function show(arg1, arg2 = anyFunction()) {
 //if no text given a anyFunction() only executed
(//如果没有给定anyFunction ()的文本仅执行)
 // its result becomes the value of text

}

A default parameter can be evaluated every time the function is called without the corresponding parameter. (每次在没有相应参数的情况下调用函数时,都可以计算默认参数。)

In the presented above example, anyFunction() is called every time show() is called. (在上面的示例中,每次调用show ()时都会调用anyFunction ()。)

Default parameters old-style

Default parameters old-style (默认参数旧式)

Old editions of JavaScript did not assist default parameters, that is why there are alternative ways that you can meet mostly in the old scripts. (旧版本的JavaScript不支持默认参数,这就是为什么您可以在旧脚本中主要满足其他方式的原因。)

For example, a clear check for being undefined:

function show(arg1, arg2) {
 if (arg2 === undefined) {
   arg2 = 'text not specified';
 }
 console.log(arg1 + " to " + arg2);
}
show("Welcome", undefined);

Or the || (OR) operator:

function show(arg1, arg2) {
 arg2 = arg2 || 'text not specified';
 //if the arg2 is false, then the text gets the default value
(//如果arg2为false ,则文本获取默认值)
 ...
}

Returning a value

Returning a value (返回值)

A function can return a value to the calling code as the result. In this simple example a function multiplies two values:

function multiply(a, b) {
 return a * b;
}
let result = multiply(2, 3);
console.log(result); // 6

We can place the directive return in any place of the function. The function stops when the execution reaches it, and the value is returned to the calling code. (我们可以将指令return放置在函数的任何位置。当执行到达时,函数停止,并将值返回到调用代码。)

There may be many incidents of return in a single function:

function checkNumber(number) {
 if (number == 10) {
   return true;
 } else {
   return false;
 }
}
let number = prompt('Guess the number?', '');
if (checkNumber(number)) {
 console.log('it’s  true');
} else {
 console.log('it’s false');
}

We can use return directive without a value, what causes the function to exit immediately. (我们可以使用不带值的return指令,这会导致函数立即退出。)

Example of the return without a value:

function showNumber(number) {
 if (!checkNumber(number)) {
   return;
 }
 console.log("Showing the number");
 //...
}

In the presented above code, if checkNumber(number) returns false, showNumber() will not move to the alert. (在上述代码中,如果checkNumber (number)返回false , showNumber ()将不会移动到警报。)

A function with an empty return directive or without it returns undefined. (>带有或不带有空return指令的函数返回undefined。)

When a function does not return a value, it is the same as when it returns undefined and an empty return. (当函数不返回值时,它与返回undefined和空返回值时相同。)

function doNothing() { /* empty */ }
console.log(doNothing() === undefined); // true

Never add a newline between return directive and the value attribute. (>切勿在return指令和value属性之间添加换行符。)

For a long expression in return, it might be attractive to put it on a separate line:

return
(long + expression + or + whatever * f(x) + f(y))

But that does not work, because JavaScript accepts a semicolon after return and that will work the same as:

return;
(long + expression + or + whatever * f(x))

As you see it effectively becomes an empty return. (正如你所看到的,它实际上变成了一个空洞的回报。)

When we want the returned expression to wrap across multiple lines, we need to start it at the same line as a return or put the opening parentheses there like this:

return (
 long + expression +
 or +
(或)
 whatever * f(x)
)

And it will work like we expect it to. (它会像我们预期的那样工作。)

Naming a function

Naming a function (命名函数)

Functions are actions and their name is generally a verb. The name should be brief, accurate, describing what the function does. (函数是动作,其名称通常是动词。名称应简短、准确,描述函数的作用。)

It is a worldwide practice to start a function with a verbal prefix which more or less describes the action. (以或多或少描述动作的口头前缀开始一个函数是一种全球性的做法。)

For example, functions that start with “show” used to show something. (例如,以“show”开头的函数用于显示某些内容。)

Function starting with… (函数开头为…)

  • “get…” – return a value, (- “get…” –返回一个值,)

  • “create…” – create something (- “创造……” –创造一些东西)

  • “calc…” – calculate something and so on. (- “calc…” –计算一些东西,以此类推。)

Examples of such names:

showMessage(..)     // shows a message
getNumber(..)          // returns the age (gets it somehow)
calcMultiply(..)         // calculates a multiply and returns the result
createForm(..)      // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false

With the function name, we can understand what kind of work it does and what kind of value it returns. (通过函数名称,我们可以了解它所做的工作以及它返回的值。)

One function should do exactly what is suggested by its name, no more. (>一个函数应该完全符合其名称的建议,而不是更多。)

Two independent actions usually do two functions, even if they are usually called together. (两个独立的动作通常执行两个函数,即使它们通常一起调用。)

Ultrashort function names

Ultrashort function names (超短函数名称)

Very often used functions sometimes have ultrashort names. (经常使用的函数有时具有超短名称。)

For instance, the jQuery framework defines a function with $. The Lodash library has its core function named . (例如, jQuery框架用$定义了一个函数。Lodash库的核心函数名为。)

But generally functions names should be brief and descriptive. (但一般来说,函数名称应简短且具有描述性。)

Functions == Comments

Functions == Comments (功能= =注释)

As we mentioned above, functions should be short and do exactly one thing. But when that thing is big, maybe it is worth it to break the function into a few smaller functions. (如上所述,函数应该很短,只做一件事。但是,当那个东西很大时,也许将函数分解为几个较小的函数是值得的。)

The reason is that the separate function is not only easier to test and debug but also it is very existence is a great comment. (原因是单独的函数不仅更容易测试和调试,而且它的存在也是一个很好的评论。)

Let’s compare the two functions showEven(num) where each one outputs even numbers up to n. (让我们比较两个函数showEven (num) ,其中每个函数输出最多为n的偶数。)

The first example uses a label:

function printEven(num) {
 for (let i = 1; i < num; i++) {
   if (i % 2 === 0) {
     console.log(i);
   }
 }
}
printEven(10);

The second example uses an additional function isEven(n) to test for primality:

function showEven(n) {
 for (let i = 2; i < n; i++) {
   if (!isEven(i)) continue;
   console.log(i); // a odd
 }
}
function isEven(num) {
 if (num % 2 === 0) {
   return true;
 } else {
   return false;
 }
}
showEven(10);

As you see it is easier to understand the second variant. We see the name of the action (isEven) instead of the code piece. (如您所见,理解第二种变体更容易。我们看到的是操作的名称(isEven) ,而不是代码段。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部