首页 > 其他 > 详细

重学ES6(三):函数和箭头函数

时间:2020-02-07 02:06:03      阅读:116      评论:0      收藏:0      [点我收藏+]

函数的参数默认值

ES5---参数的默认值通常都是写在函数体中,不传参即用默认参数

// ES5
// 设置参数默认值,未传入参数时按照默认值
function f(x, y, z) {
  if (y === undefined) {
    y = 7
  }
  if (z === undefined) {
    z = 42
  }
  return x + y + z
}

console.log(f(1)) // 50
console.log(f(1, 8, 43)) // 52

ES6---参数的默认值通常写在参数中,不传参即用默认参数

  • 函数参数是从左到右解析,如果没有默认值会被解析成 undefined,所以传入undefined即可跳过有默认值的参数

// ES6参数默认值
function f (x, y = 7, z = 42) {
  return x + y + z
}

console.log(f(1)) // 50
console.log(f(1, undefined,50)) // 传入undefined即可跳过有默认值的参数

// 参数甚至可以是其他参数的运算表达式
function fn (x, y=7, z = x + y) {
  return x * y *z
}

console.log(fn(1, undefined)) //56

 

不定参数函数

当遇到类似求和,字符串拼接等等不确定参数的情况下,需要接收所有参数再处理

ES5 --- 转换参数至数组

function sum () {
  let num = 0

  // ES5
   Array.prototype.forEach.call(arguments, function (item) {
     num += item * 1
   })
  return num
}

console.log(sum(1, 2, 3)) // 6

ES6 --- 转换参数至数组

function sum () {
  let num = 0

  // ES6
  // arguments获取到所有参数,arguments是伪数组,Array.from转化为数组
  Array.from(arguments).forEach(function (item) {
    num += item * 1
  })
  return num
}

console.log(sum(1, 2, 3)) // 6

 

Rest Parameter 

  • 用法  function (...参数名) { } 
  • ...表示函数所有的参数都位于参数名变量中,所以只需要遍历该参数(数组)即可
function newsum (...nums) {
  // Rest Parameter
  // ...表示函数所有的参数都位于nums变量中,所以只需要遍历nums即可
  let num = 0
  nums.forEach(function (item) {
    num += item * 1
  })
  return num
}

console.log(newsum(3, 5, 8)) // 16
  • 也可配合其他参数使用
// Rest Parameter 也可以和其他参数一起来用
function newsumtwo (base, ...nums) {
  // Rest Parameter
  let num = 0
  nums.forEach(function (item) {
    num += item * 1
  })
  return base*2 + num
}

console.log(newsumtwo(3, 5, 8)) // 19

 

Spread Operator

  • Spread Operator是Rest Parameter的反操作

  • Spread Operator把固定的数组内容“打散”到对应的参数,而不必使用arr[0],arr[1]这种数组索引进行传参

// Spread Operator是Rest Parameter的反操作
// Rest Parameter把不定的参数“收敛”到数组(定义于函数的参数---收)
// Spread Operator把固定的数组内容“打散”到对应的参数(定义与传参---传)
let data = [5,7,9]
console.log(sum(...data)) // 21

 

箭头函数

传统函数 function (参数)  {...}

箭头函数 (参数) => {...}

// 箭头函数
let hello = (name) => {
  console.log(‘hello‘,name)
}
hello(‘xz‘)

//箭头后为表达式,表达式的值就作为返回值返回
let sum = (x, y, z) => x + y + z
console.log(sum(1,2,3)) // 6

 

this指向问题

传统函数:

  • 谁调用函数,this指向谁

箭头函数:

  • 箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。
  • 箭头函数中this的指向在定义时就被规定,和调用者无关

  • this绑定的是最近一层非箭头函数的this

  • 箭头函数中的this,首先从它的父级作用域中找,如果父级作用域还是箭头函数,再往上找,如此直至找到this的指向

// this指向(传统函数)
let test = {
  name: ‘test‘,
  say: function () {
    console.log(this.name)
  }
}

// 谁调用函数,则this指向其
test.say() // test
// this指向(箭头函数)
let testtwo = {
  name: ‘test‘,
  say: () => {
    console.log(this.name)
  }
}

//this绑定的是最近一层非箭头函数的this
testtwo.say() // undefined

 

重学ES6(三):函数和箭头函数

原文:https://www.cnblogs.com/xzweb/p/12271164.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!