Eloquent JavaScript - Functions

98 阅读2分钟

关于return关键词

A return keyword without an expression after it will cause the function to return undefined. Functions that don't have a return statement at all, such as makeNoise, similarly return undefined.

const makeNoise = function() {
    console.log("Ping!"); 
}; 
/* console.log(makeNoise())输出的结果将是undefined */
console.log(makeNoise()); 

Bindings and Scopes

内容待补充

Functions as Values

A binding that holds a function is still a regular binding and can, if not constant, be assigned a new value. 举一个例子:

let function1 = function () {
  console.log("function1 prints Hello World!");
};
function1(); 

function1 = function () {
  console.log("function1 has now been assigned a new function value.");
};
function1();

Declaration Notation

除了上面makeNoise这种声明函数的方式,另一种方式是直接把function关键词放在最前面:

function square(x) {
    return x * x; 
}

两种声明方式的区别在于:

  • 第二种(function declaration)声明方式括号后不需要加semicolon
  • 第二种方式声明的函数,不受自上而下的控制流的约束。

Function declarations are not part of the regular top-to-bottom flow of control.

console.log(`The future says: ${future()}.`); 

function future() {
    return "You'll never have flying cars"; 
}

正如上面例子所示,虽然future()是声明在console.log之后,但不影响程序运行。

The Call Stack

计算机会将函数调用(function call)的context存储在memory里面。

The place where the computer stores this context is the call stack. Every time a function is called, the current context is stored on top of this stack. When a function returns, it removes the top context from the stack and uses that context to continue execution. 这里作者举了一个先有鸡还是先有蛋的例子来展示,当调用栈的内存被存满的时候,运行会显示“out of stack space”之类的信息。

function chicken() {
  return egg();
}

function egg() {
  return chicken();
}

console.log(chicken() + " came first.");

很明显chicken()会陷入死循环,然后console会显示Maximum call stack size exceeded

1616909896(1).png

Closure

作者在这部分内容里举了一个例子:

function multiplier(factor) {
  return (number) => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));

这里multiplier()返回了一个新的函数,然后twice也是一个函数。