函数

在 JS 中函数为一等公民,即函数和其他数据类型一样,每个 JS 函数实际上都是一个Function对象,可以赋值给其他变量,可以作为参数传入另一个函数,或者作为其他函数的返回值。

函数对象属性

(function() {}).__proto__ === Function.prototype; // true
function add(a, b) {
  return a + b;
}

console.log(test.length); // 2 参数数量
console.log(test.name); // add 函数名,匿名函数的返回值为 anonymous

Arguments

arguments是一个对应于传递给函数的参数的类数组对象,是所有函数(箭头函数除外)的局部变量。

function func1(a, b, c) {
  console.log(arguments[0]);

  console.log(arguments[1]);

  console.log(arguments[2]);
}
func1(1, 2, 3);

箭头函数

箭头函数表达式的语法相比于函数表达式更简洁,箭头函数没有自己的thisargumentssupernew.target,没有prototype属性。

  • 箭头函数适合作为纯函数使用,适合用在回调场景
  • 箭头函数不适合作为 Class 函数或对象函数使用
  • 箭头函数不能使用 new 关键字,因为它没有自己的 this,无法用于构造函数

  • 箭头函数没有自己的this,而是继承其定义时的外部 this(也称为 词法作用域)。详见this

  • 箭头函数的this是不可变的,不能使用call()apply()bind()进行this绑定
  • 没有prototype属性和自己的this,所以不可用作为构造函数使用,会报错
  • 箭头函数没有自己的arguments对象,而是继承自外层函数的 arguments
  • 不可用使用yield,不能用作 Generator 函数

Class 中的箭头函数和普通成员函数区别

class Person {
  constructor(name, age) {
    this.state = {
      name, age
    }
  }
  // 箭头函数
  getName = () => {
    console.log('arrow: ', this)
    console.log('name: ', this.state.name)
  }
  // 普通函数
  getAge() {
    console.log('function: ', this)
    console.log('age: ', this.state.age)
  }
}
const lee = new Person('lee', 21);
lee.getName();
// arrow:  Person {state: {…}, getName: ƒ}
// name:  lee
lee.getAge();
// function:  Person {state: {…}, getName: ƒ}
// age:  21

lee.hasOwnProperty('getName') // true
lee.hasOwnProperty('getAge') // false
  • 无论是箭头函数还是普通函数this都执行对象实例
  • 普通函数方法会绑定到对象原型链
  • 箭头函数方法会绑定到对象实例

results matching ""

    No results matching ""