JS 中 函数 的一些概念

1. 一个对象,实现了 .call 方法,就是一个函数,据说出自 ECMAScript 里的一句话,但是本人并没看过,无从证实。

2. 函数身上的属性:length、name、caller

  • length 函数参数的个数
  • name 函数的名字
  • caller 指的就是他在哪调用了,如果是在全局调用,值就是null,如果在别的函数里面调用,值就是函数的应用地址(函数)
function fn(a, b) {
  console.log(fn.caller); // ƒ fn2() { fn() }
};

function fn2() {
  fn();
};

fn2();

console.log(fn.name); // fn
console.log(fn.length); // 2

3. 参数集合 arguments

类数组

function fn2() {
  console.log(arguments); // => Arguments(3) [1, "3", true, callee: ƒ, Symbol(Symbol.iterator): ƒ]... 一个函数的参数和其他属性
  console.log([...arguments]); // => [1, "3", true]  类数组转数组,为了可以使用数组的方法
  console.log(arguments.length); // => 3
  console.log(arguments[2]); // => true
  console.log(arguments.callee) // => ƒ fn(a, b) {...}  当前正在运行的函数,使用场景:佚名函数中做递归
};

fn2(1, "3", true);

4. 函数表达式和函数声明

var init = function() { }; 是函数表达式,函数在代码执行的到当前行的时候才被执行,init 才被赋值。
function init() {} 是函数的声明,和 var 一样,会被提前到代码最前面定义。
下面的两个例子:

foo(); // 在函数声明之后调用 foo,可以正常调用。因为 foo 被提前到最前面定义了。
function foo() {
  return true;
}

foo2(); // 在函数表达式之前调用函数,报错。因为这时候还没有 foo2 这个变量。
var foo2 = function() {
  return true;
};

5. 函数的 this 指向

6. 箭头函数

7. 递归

  let num = 0;
  let fn = function () {
    num++;
    console.log(num); // 1 ~ 10
    if (num < 10) { // 注意判断条件,无限递归直接卡死
      fn();
    };
  };
  fn();

8. 回调函数

  let ajax = function (callback) { // 模拟一个异步操作
    setTimeout(() => {
      callback && callback("Hello world") // 当获取到异步操作结束时,执行回调函数,获取数据
    }, 1000);
  };

  let cfn = function (p) {
    console.log(p); // "Hello world"
  }

  ajax(cfn);
原文地址:https://www.cnblogs.com/MrZhujl/p/15044738.html