美文网首页
Function expression and arrow fu

Function expression and arrow fu

作者: meteornnnight | 来源:发表于2018-12-18 11:10 被阅读0次

引言:

Why I have to learn function and now prefer using it as much as possible? Well, primarily there are two reasons: First of all, functions make codes more readable; Secondly, it can avoid the duplication of codes again and again.

举个栗子:

我们来看看function如何让代码结构更具有易读性。如果现在我们的任务是:打印出2到n区间内的所有素数。

approach 1:
outer:
for( let i = 2; i <= n; i++)
{
  for( let j = 2; j <= i; j++)
  {
      if (i % j == 0) continue outer;
 // not a prime number, continue to next iteration of outer loop.
  }
  alert( i+"\n");
}
approach 2 (using function isPrime() ):
function isPrime(n)
{
  for( let i = 2; i < n; i++)
  {
    if ( n % i == 0)  return false;
  }
  return true;
}
for( let i = 2; i <= n; i++)
{
  if( isPrime(i) ) alert( i+"\n"); // This part is more readable!
}

2. Function expression

2.1 syntax

在一般情况下,我们定义函数prefer function declaration的方式,也就是:

function name(arg1,arg2,...,argN)
{
  //body, 如果没有return value, 默认函数return undefined.
}

可以看到function declaration的code是statement, 包含在代码块中常常看到的花括号{},现在我们提出一种新的函数定义方式:

let sum=function( a, b ){
return a+b;
};  // " ;"  is added here because it is a expression.

function expression的语法更像是expression,所以结尾会有;

2.2.1 用法1:

function ask( question, yes, no)
{
  if( confirm( question ) ) yes();
  else no();
}
ask("Are you sure?",
  function(){ alert("Ok, I get it.") },
  function(){ alert("I will cancel it.") }
);

2.2.2 用法2:

let welcome;
let age=prompt("How old are you?","");
welcome= (age >= 18)
        ? function( ){ alert("adult"); }
        : function( ){ alert("teenager"); } ;
welcome();
// rewrite with arrow function
let age=prompt("How old are you?","");
let welcome= (age >= 18)
        ? () => alert("adult")
        : () => alert("teenager");
welcome();

Summary:
在JavaScript中,function name也可以看成是一个variable, 存放的value是function的source code, 其他primitive type的variable存放的value是data, function variable存放的value可以看成是action.

3. Arrow function

3.1 Syntax

let sum=(a,b) => a+b;
let double=n => n*n; //只有一个参数时,()可以省略
let greeting=() => alert("Hello"); //没有参数的时候,()不可以省略

(para1, para2,..., param) => statement/expression如果arrow function的代码语句部分是statement, 函数return undefined; 如果是expression, 函数return expression。

相关文章

网友评论

      本文标题:Function expression and arrow fu

      本文链接:https://www.haomeiwen.com/subject/rlukkqtx.html