1.函数参数的默认值
- ES5中函数参数的默认值的处理
function f(x, y, z) {
if (y === undefined) {
y = 7;
}
if (z === undefined) {
z = 8;
}
return x + y + z;
}
console.log(f(1))
如果没有值,会被解析为undefined
如果想让具体某个参数使用默认值,可以使用undefined进行赋值:
function f(x, y = 7, z = 42) {
return x + y + z;
}
console.log(f(1, undefined, 43)) //51
- ES6中函数参数的默认值的处理
function f(x, y = 7, z = 8) {
return x + y + z
}
console.log(f(1))
其中函数参数也可以是表达式的形式:
function f(x, y = 7, z = x + y) {
return x + y + z
}
console.log(f(1))
2.处理不确定参数
- ES5中处理不确认参数的方法
function sum() {
let num = 0;
Array.prototype.forEach.call(arguments, function (item) {
num += item * 1;
})
return num
}
console.log(sum(1,2,3,4,5)) // 15
- ES6中处理不确认参数的方法
function sum(base, ...nums) { //其中base是传进来的第一个参数,...nums是剩下的所有参数
let num = 0;
nums.forEach(function (item) {
num += item * 1
})
return base*3 + num
}
console.log(sum(1, 2, 3, 4, 5)) // 17
3.rest参数的逆运算
- ES5中rest参数逆运算的做法
function sum(x = 1, y = 2, z = 3) {
return x + y + z
}
let data = [4,5,6]
console.log(sum(data[0],data[1],data[2])) //15
console.log(sum.apply(this,data)) //15
- ES6中参数逆运算的做法
function sum(x = 1, y = 2, z = 3) {
return x + y + z
}
let data = [4,5,6]
console.log(sum(...data)) //15
4.1.箭头函数定义
例如:
let hello = () => {
console.log('this is a Arrow Function')
}
带有参数的时候:
let hello = (name) => {
console.log('this is a Arrow Function', name)
}
或者
let hello = name => {
console.log('this is a Arrow Function', name)
}
如果只有一个参数,可以省略括号,如果大于一个参数一定要带上括号。
- 如果返回值是表达式,则可以省略return和{}
let pow = x => x*x
- 如果返回值是字面量对象,一定要使用小括号包起来
let person = (name) =>{
age: 18,
addr: 'ChengDu'
}
4.2箭头函数与普通函数this的比较
箭头函数和普通函数对this的处理方式是截然不同的。
- 普通函数中对this的处理:
let test = {
name: 'test',
say: function(){
console.log(this.name)
}
}
console.log(test.say()) //test
其中say在被调用之后,this指向的是调用say方法的对象,显示是test对象,所以this===test,那么this.nameu也就是test.name。
- 箭头函数中的处理:
let test = {
name: 'test',
say: () => {
console.log(this.name, this)
}
}
console.log(test.say()) //undefined
因为箭头函数中对this的处理是定义时,this的指向也就是test外层所指向的window,而window没有name属性,所以结果是undefined。