函数

20 阅读2分钟

箭头函数

所有使用函数表达式的位置,均可以替换为箭头函数

/**eg1*/
const sum = function(a, b) {
  return a + b;
}

// 箭头函数写法
const sum = (a, b) => a + b

/**eg2*/
dom.onclick = function(e){
  // ....
}

// 箭头函数写法
dom.onclick = e => {
  // ...
}

/**eg3*/
setTimeout(function(){
  // ...
}, 1000)

// 箭头函数写法
setTimeout(() => {
  // ...
}, 1000)

箭头函数有以下特点:

  1. 不能使用new调用
  2. 没有原型,即没有prototype属性
  3. 没有arugments
  4. 没有this :箭头函数的this永远指向箭头函数定义位置的this,因为箭头函数会绑定this。根本原因是它没有this,它里面的this使用的是外层的this
const counter = {
  count: 0,
  start: function(){
    // 这里的 this 指向 counter
    setInterval(() => {
      // 这里的 this 实际上是 start 函数的 this
      this.count++;
    }, 1000)
  }
}

箭头函数的这些特点,都足以说明:箭头函数特别适用于那些临时需要函数的位置

剩余参数

ES6不建议再使用arguments来获取参数列表,它推荐使用剩余参数来收集未知数量的参数

// ...args为剩余参数
function method(a, b, ...args){
  console.log(a, b, args)
}

method(1, 2, 3, 4, 5, 6, 7); // 1 2 [3, 4, 5, 6, 7]
method(1, 2); // 1 2 []

剩余参数只能声明为最后一个参数

参数默认值

ES6提供了参数默认值,当参数没有传递或传递为undefined时,会使用默认值

/**eg1*/
// 对参数 b 使用了默认值1
function method(a, b = 1){
  console.log(a, b)
}
method(1, 2); // 1  2
method(1); // 1 1
method(1, undefined); // 1 1
/**eg2*/
// 对参数 b 使用了默认值1, 对参数 c 使用默认值2
const method = (a, b = 1, c = 2, d) => {
  console.log(a, b, c, d)
}
method(1, 2); // 1 2 2 undefined
method(1); // 1 1 2 undefined
method(1, undefined, undefined, 4); // 1 1 2 4

类语法

function A(){}
A(); // 直接调用
new A(); // 作为构造函数调用

这种做法无法从定义上明确函数的用途,因此,ES6推出了一种全新的语法来书写构造函数

/**eg1*/
// 旧的写法
function User(firstName, lastName){
  this.firstName = firstName;
  this.lastName = lastName;
  this.fullName = `${firstName} ${lastName}`;
}
User.isUser = function(u){
  return !!u && !!u.fullName
}
User.prototype.sayHello = function(){
  console.log(`Hello, my name is ${this.fullName}`);
}

// 新的等效写法
class User{
  constructor(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = `${firstName} ${lastName}`;
  }
  
  static isUser(u){
  	 return !!u && !!u.fullName
  }
  
  sayHello(){
    console.log(`Hello, my name is ${this.fullName}`);
  }
}

/**eg2*/
function Animal(type, name){
  this.type = type;
  this.name = name;
}

Animal.prototype.intro = function(){
  console.log(`I am ${this.type}, my name is ${this.name}`)
}

function Dog(name){
  Animal.call(this, '狗', name);
}

Dog.prototype = Object.create(Animal.prototype); // 设置继承关系

// 新的方式

class Animal{
  constructor(type, name){
    this.type = type;
    this.name = name;
  }
  
  intro(){
    console.log(`I am ${this.type}, my name is ${this.name}`)
  }
}

class Dog extends Animal{
 	constructor(name){
    super('狗', name);
  }
}

image.png