记es6箭头函数特性

991 阅读3分钟

ES6处理默认参数

function person(name = 123, age = 456){
    // es5 需要自行判断处理
    // name = typeof(name) === 'undefined' ? 123 : name
    console.log(name, age)
}
person() // 123 456
person(null, null) // null null

默认参数null是一个合法值,只有函数参数为undefined时才会使用默认值。 默认参数也可以定义为函数变量

function obj(){
    return {
    	aa:123,
        bb:456
    }
}
function person(name = obj()){
    console.log(name)
}
person() // {xxx}
person('111') // 111

参数表达式只有在调用且没有传入参数才会执行。

function person(name=nickName, nickName){
    console.log(name, nickName)
}
person() // Cannot access 'nickName' before initialization

这是在定义变量前去访问,会报错,暂时性死区。

arguments的区别

es5 非严格模式下,函数命名的参数变化会体现在arguments对象上,即在非严格模式下它跟形参是映射关系。

function test(a, b){
    console.log(arguments) // [1,2]
    console.log(a)
    console.log(b)
    a = 'a'
    b = 'b'
    console.log(arguments) // ['a','b']
}
test(1,2) 

在严格模式下,无论参数如何变化,arguments不会随之改变。

function test(a, b){
    'use strict'
    console.log(arguments) // [1,2]
    console.log(a)
    console.log(b)
    a = 'a'
    b = 'b'
    console.log(arguments) // [1,2]
}
test(1,2) 

如果一个函数使用了默认参数值,那么arguments对象的行为都将与JavaScript中的严格模式下保持一致。

 function test(a, b = 2) {
    a = 12
    b = 10
    console.log(arguments) // [1] 因为arguments对象获取的是实参
}
test(1)

平时开发会写成...params获取已知参数外的数据。

function test(a, ...params){ // rest parameter must formal parameter
    console.log(params) // [3, 5]
}
test(1, 3, 5)

还有一点,不定参数不能定义在对象字面量的setter中,因为setter函数只接收一个函数,写成不定参数之后就会是一个数组,这样就会导致程序异常。

let obj = {
  set name(...params) {}
}
// Setter function argument must not be a rest parameter
  • 箭头函数没有arguments
let test1 = () => {
    console.log(arguments)
}
test1(123) // arguments is not defined

箭头函数找arguments对象只会找外层非箭头函数的函数,如果外层是一个非箭头函数的函数如果它也没有arguments对象也会中断返回,就不会在往外层去找

function test2(a, b, c){
    return () => {
    	console.log(arguments) // [1]
    }
}
test2(1)()
  • 箭头函数this值 箭头函数的this值,取决于函数外部非箭头函数的this值,如果上一层还是箭头函数,那就继续往上找,如果找不到那么this就是window对象
let person = {
    test: () => {
        console.log(this)
    },
    fn(){
        return () => {
            console.log(this)
        }
    }
}
person.test()  // window
person.fn()()  // person对象

箭头函数不能改变this指向

let person = {}
let test = () => console.log(this)
test.bind(person)()
test.call(person)
test.apply(person)

在预编译的时候,this 就已确定。

  • 箭头函数不能用new关键字声明
let test = () => {}
new test() // Uncaught TypeError: test is not a constructor
  • 箭头函数没有原型prototype JavaScript中所有的函数都有prototype属性吗,这个是错误的。
let test = () => {}
test.prototype // undefined
test.__proto__ === Function.prototype // true
// 箭头函数不能重复命名参数
let bbb = (b, b, b) => {
} 
// Uncaught SyntaxError: Duplicate parameter name not allowed in this context
let bb = function(b, b, b){
}
// es5 不会报错

汇总:

  • ES6处理默认参数,默认参数可以是函数或变量
  • 箭头函数没有arguments,其值取决于外层非箭头函数的值,(外层无就会报错)。
  • this不同, 取决于外层非箭头函数的this的值
  • 没有原型prototype属性
  • 箭头函数不能new 操作