JavaScript 第十章总结:first class functions 前言 function expression 的定义 使用 function 的三种特殊的情况 使用 sort() 这个 method

这一章的内容是 advanced knowledge and use of functions. 讲了关于 function 的使用的一些特殊的方面。

function expression 的定义

格式:

var fly = function(num){
for(var i = 0; i < num; i++) {
console.log("Flying!");
}
};

fly(3);

与 function declaration 的两个不同之处

  1. runtime 不同:function declaration 是在浏览器执行代码之前先进行扫描,并创建相应的函数,function expression 是在浏览器执行代码的时候进行创建相应的函数。
  2. function naming 方式不同: function declaration 是将 reference 赋值给函数名,而使用 function expression 不需要 provide a name.

关于第二点,书中最后总结:

  1. When the browser evaluates a function declaration, it creates a function as well as a variable with the same name as the function, and stores the function reference in the variable.
  2. When the browser evaluates a function expression, it creates a function, and it's up to you what to do with the function reference.

使用 function 的三种特殊的情况

定义

first class values: function 可以作为 value 来使用,书中的描述如下:

First class: a value that can be treated like any other value in a programming language, including the ability to be assigned to a variable, passed as an argument, and returned from a function.

功能:

  1. Assign a value to a function
  2. Pass a function to a function
  3. Return a function from a function

无论是 function declaration 还是 function expression, 它们的名字都是函数的 reference 值,因此可以利用、传递这个值来 invoke 一个 function. 

1. Assign the value to a function

格式:var fly = [function expression]

2.Pass the function to a function

格式:function boo(aFunction){
aFunction("boo");
}
function fun(echo){
}
boo(fun);

3. Return a function from a function

使用 sort() 这个 method

sort() 介绍:

sort 可接受一个数字作为参数,通过这个参数的情况进行排序:

  1. >0的时候:place the first item after the second item
  2. =0的时候: leave the items in place
  3. <0 的时候:place the first item before the second item

总结的两种情况:

可以使用一个自定义的 compare(num1,num2) 函数,来得到上面所要求的参数,并且分下面两种情况:

  • ascending:if(num1>num2){return 1;}或者 return(num1-num2)
  • descending:if(num1<num2){return 1;}或者 return(num2-num1)