ES6笔记--函数

函数默认参数:

 在ES5中,我们给函数传参数,然后在函数体内设置默认值,如下面这种方式。

 function a(num, callback) {
      num = num || 7
      callback = callback || function (data) {console.log('ES5: ', data)}
      callback(num * num)
    }
    a() //ES5: 49,不传参输出默认值

而在ES6中,我们使用新的默认值写法:

function a(num = 6, callback = function (data) {console.log('ES6: ', data)}) {
      callback(num * num)
    }
    
    a() //ES6: 36, 不传参输出默认值

使用ES6的默认值写法可以让函数体内部的代码更加简洁优雅

块级函数

严格模式下:在ES6中,你可以在块级作用域内声明函数,该函数的作用域只限于当前块,不能在块的外部访问。

 "use strict";
    if(true) {
      const a = function(){
      
      }
    } 

非严格模式:即使在ES6中,非严格模式下的块级函数,它的作用域也会被提升到父级函数的顶部。建议尽量使用严格模式。

箭头函数(=>)

const arr = [5, 10]
const s = arr.reduce((sum, item) => sum + item)
console.log(s) // 15

箭头函数提供了一种更加简洁的函数书写方式;当箭头函数没有参数或者有多个参数,要用 () 括起来。

当箭头函数函数体有多行语句,用 {} 包裹起来,表示代码块,当只有一行语句,并且需要返回结果时,可以省略 {} , 结果会自动返回。

var f = (a,b) => {
 let result = a+b;
 return result;
}
f(6,2);  // 8

当箭头函数要返回对象的时候,为了区分于代码块,要用 () 将对象包裹起来

// 报错
var f = (id,name) => {id: id, name: name};
f(6,2);  // SyntaxError: Unexpected token :
 
// 不报错
var f = (id,name) => ({id: id, name: name});
f(6,2);  // {id: 6, name: 2}

注意点:没有 this、super、arguments 和 new.target 绑定。

var func = () => {
  // 箭头函数里面没有 this 对象,
  // 此时的 this 是外层的 this 对象,即 Window 
  console.log(this)
}
func(55)  // Window 
 
var func = () => {    
  console.log(arguments)
}
func(55);  // ReferenceError: arguments is not defined

箭头函数和普通函数的区别是:

1、箭头函数没有this,函数内部的this来自于父级最近的非箭头函数,并且不能改变this的指向。

2、箭头函数没有super

3、箭头函数没有arguments

4、箭头函数没有new.target绑定。

5、不能使用new

6、没有原型

7、不支持重复的命名参数。

你可能感兴趣的:(前端学习)