ES6之函数的扩展二

ES6之函数的扩展一 传送门

9.3 函数length属性

函数的length属性,不包含rest参数

console.log((function (a) {}).length) // 1
console.log((function (...a) {}).length) // 0
console.log((function (a1,b,...a) {}).length) // 2

10:严格模式

在 ES5 中,允许函数内部显示定义 严格模式 ‘use strict’
ES6 中,函数参数使用了参数默认值,对象解构参数和扩展运算符的话,如果在函数内部显示定义了严格模式,会出现错误

10.1 函数中定义严格模式产生错误

10.1.1 case 1: 参数默认值
function fun101 (a,b=a) {
    'use strict'
    console.log(a,b)
}
fun101(12,24) // Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list
10.1.2 case 2: 对象解构
function fun102({a,b=1}) {
    'use strict'
    console.log(a,b) // Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list
}
fun102(2,6)
10.1.3 case 3: rest 扩展运算符
function fun103 (...items) {
    'use strict'
    console.log(items) // Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list 
}
fun103(1,2,3)

流程一:函数体中的严格模式,是适用于函数体和函数参数;
流程二:函数执行顺序是先从上往下,先执行函数参数,再执行函数体;
流程三:产生的错误:'use strict’在函数体声明的;
流程四:但是函数参数不知道当前是以严格模式运行。(这时候函数参数根据变量作用域,已经运行结束),就会产生错误

  • 注:为了避免如此复杂的行为,标准协议禁止了这种用法,在使用参数默认值,对象解构参数和扩展运算符的情况下,不能显示指定严格模式

10.2 避免严格模式错误

10.2.1 case 1 在函数外部定义 严格模式 全局
'use strict'
function fun104(x,y=x){
    console.log(y) // 10
}
fun104(10) 
10.2.2 case 2 函数嵌套 中使用 严格模式
const fun105 = (x) => {
    console.log(x)
    return function fun (x,y=x) {
        console.log(y) // 8
    }
    fun(x)
}
fun105(8)

11: name 属性

11.1 case 1

function fun1101(){}
console.log(fun1101.name) // fun1101

11.2 匿名函数

返回变量名

const fun1102 = function () {}
console.log(fun1102.name) // fun1102

11.3 具名函数

返回实际函数名

const fun1103 = function bar () {}
console.log(fun103.name) // fun1103

11.4 构造函数

console.log((new Function).name) // anonymous

11.5 bind方法

修改this指向

function fun1104 () {}
console.log(fun1104.bind({}).name) // bound fun1104
console.log((function(){}).bind({}).name) // bound

12 箭头函数

如果箭头函数代码块部分多余一条语句,需要使用大括号包括起来,并用return进行返回

12.1 case 1

let fun1201 = () => { a1: 1 }
console.log(fun1201()) // undefined

12.2 简化函数

let arr = [1,2,3,4,5,6]
let arr1 = arr.map((x) => x * 2)
console.log('arr1:',arr1) // [2, 4, 6, 8, 10, 12]

12.3 sort 排序

let values = [1,6,8,3,5,6,3,2,4,6]
let sort1 = values.sort(( a,b ) => a-b)
console.log(sort1) // [1, 2, 3, 3, 4, 5, 6, 6, 6, 8]

12.4 rest参数与箭头函数

let arr1204 = (...nums) => nums
console.log(arr1204(1,2,3,4,5,6,7,8)) // [1, 2, 3, 4, 5, 6, 7, 8]

rest形式的参数本身就是一个数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值