ES6学习第六节:Function扩展

  • 函数参数默认值
// ES5
function log(x, y) {
  y = y || 'World';
  console.log(x, y);
}

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello World

// ES6
function log(x, y = 'World') {
  console.log(x, y);
}

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello
  • 与解构赋值默认值结合使用
function foo({ x, y = 5 }) {
  console.log(x, y)
}

foo({}) // undefined 5
foo({ x: 1 }) // 1 5
foo({ x: 1, y: 2 }) // 1 2
foo() // TypeError: Cannot read property 'x' of undefined

// 解决传入非对象报错
function foo({x, y = 5} = {}) {
  console.log(x, y);
}
foo() // undefined 5
  • 参数默认值的位置
// 例一
function f(x = 1, y) {
  return [x, y];
}

f() // [1, undefined]
f(2) // [2, undefined])
f(, 1) // 报错
f(undefined, 1) // [1, 1]

// 例二
function f(x, y = 5, z) {
  return [x, y, z];
}

f() // [undefined, 5, undefined]
f(1) // [1, 5, undefined]
f(1, ,2) // 报错
f(1, undefined, 2) // [1, 5, 2]

// 如果传入undefined,将触发该参数等于默认值,null则没有这个效果。
function foo(x = 5, y = 6) {
  console.log(x, y);
}

foo(undefined, null) // 5 null
  • 函数的length属性
(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
  • 作用域

一旦设置了参数的默认值,函数进行声明初始化时,参数会形成一个单独的作用域(context)。等到初始化结束,这个作用域就会消失。这种语法行为,在不设置参数默认值时,是不会出现的。

var x = 1;

function f(x, y = x) {
  console.log(y);
}

f(2) // 2
  • rest参数

ES6 引入 rest 参数(形式为...变量名),用于获取函数的多余参数,这样就不需要使用arguments对象了。rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。

// Rest参数
function add(...values) {
  let sum = 0
  for (let item of values) {
    sum += item
  }
  return sum
}
console.log(add(3, 4, 5))

// 两种方式实现数组排序对比
function sortNumbers() {
  // arguments对象不是数组,而是一个类似数组的对象。所以为了使用数组的方法,必须使用Array.prototype.slice.call先将其转为数组。
  return Array.prototype.slice.call(arguments).sort()
}
const sortNumbers = (...numbers) => numbers.sort()
console.log(sortNumbers(1, 2, 5, 8, 4, 7, 9, 2, 7))

rest 参数之后不能再有其他参数(即只能是最后一个参数),否则会报错。

// 报错
function f(a, ...b, c) {
  // ...
}

函数的length属性,不包括 rest 参数。

(function(a) {}).length  // 1
(function(...a) {}).length  // 0
(function(a, ...b) {}).length  // 1
  • name属性

函数的name属性,返回该函数的函数名。

function fn() {}
console.log(fn.name) // fn
var fn = function() {}
console.log(fn.name) // fn
// Function构造函数返回的函数实例,name属性的值为anonymous。
console.log(new Function().name) // anonymous
// bind返回的函数,name属性值会加上bound前缀。
console.log(fn.bind({}).name) // bound fn
  • 箭头函数

(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。
(4)不可以使用yield命令,因此箭头函数不能用作 Generator 函数。

// 箭头函数
var f = v => v
var f = function(v) {
  return v
}

var f = () => 5
var f = function() {
  return 5
}
var sum = (sum1, sum2) => sum1 + sum2
var sum = function(sum1, sum2) {
  return sum1 + sum2
}

// 多个返回语句使用大括号括起来
var more = a => {
  if (a > 100) {
    return 100
  } else {
    return 99
  }
}
console.log(more(99), more(101))

// 返回对象时使用括号括起来
var backObj = name => ({ name: name, temp: 'temp' })
console.log(backObj('Changlau'))

使表达式更简洁

const isEven = n => n % 2 === 0;
const square = n => n * n;

简化回掉函数

;[1, 2, 3].map(function(item) {
  return item * item
})
;[1, 2, 3].map(item => item * item)

// 正常函数写法
var result = values.sort(function (a, b) {
  return a - b;
});
// 箭头函数写法
var result = values.sort((a, b) => a - b);

// 箭头函数和rest参数结合
const headAndTail = (head, ...tail) => [head, ...tail]
console.log(headAndTail(1, 2, 3, 4, 5)) // [1,2,3,4,5]
  • 箭头函数的this

箭头函数根本没有自己的this,导致内部的this就是外层代码块的this。正是因为它没有this,所以也就不能用作构造函数。

function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => this.s1++, 1000);
  // 普通函数
  setInterval(function () {
    this.s2++;
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0
  • 箭头函数中的this转为ES5
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}
  • 不适合使用箭头函数的场景
// cat.jumps调用函数,此时函数内部指向全局变量this,不能返回争取的结果
const cat = {
  lives: 9,
  jumps: () => {
    this.lives--;
  }
}

//  动态this场景,此时this也指向全局对象,不是被点击的button对象
var button = document.getElementById('press');
button.addEventListener('click', () => {
  this.classList.toggle('on');
});

猜你喜欢

转载自blog.csdn.net/weixin_34295316/article/details/86901427