// 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参数默认值 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
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
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
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是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
// 箭头函数 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指向(传统函数) 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
原文:https://www.cnblogs.com/xzweb/p/12271164.html