函数

94 阅读1分钟
函数类型
function add(a:number,b:number):number{
    return a+b
}

书写完成版

const add:(a:number,b:number)=>number=function(a,b){
    return a+b
}
可选参数

我们可以在参数后面加?来表示该参数为可选参数

const add:(a:number,b?:number)=>number=function(a,b){
    if(b!==undefined){
        return a+b
    }
    return a
}
console.log(add(1))  //1
console.log(add(1,2))  //3
默认参数

我们可以使用=给形参赋值为默认值

const add:(a:number,b?:number)=>number=function(a,b=1){
    return a+b
}
console.log(add(1))  //2
剩余参数

在以前我们可以使用arguments来访问所有参数,现在可以使用...扩展运算符来拿到剩余参数

const add:(a:number,b:number,c:number,d:number,e:number)=>number=function(a,...rest){
    console.log(rest) //[2,3,4,5]
    return a+rest.reduce((x,y)=>x+y)
}
console.log(add(1,2,3,4,5)) //15
this

每个函数都有自己的this指向,this的值在函数被调用的时候才会指定。指向被调用的对象(箭头函数除外)

let person={
    name:'bom',
    age:18,
    speak:function(){
        return function(){
            return `我的名字是${this.name},今年${this.age}岁`
        }
    }
}
console.log(person.speak()())  //error: this上没有name和age

我们引入箭头函数

let person={
    name:'bom',
    age:18,
    speak:function(){
        return ()=>{
            return `我的名字是${this.name},今年${this.age}岁`
        }
    }
}
console.log(person.speak()())  //我的名字是bom,今年18岁

由上可见,箭头函数没有自己的this,会顺着作用域往上查找到到父级函数的this

this参数

我们可以手动指定this,箭头函数的thisvoid

interface PersonType{
    name:string;
    age:number;
    speak:(this: PersonType)=>(this: void)=>string
}

let person: PersonType={
    name:'bom',
    age:18,
    speak:function(){
        return ()=>{
            return `我的名字是${this.name},今年${this.age}岁`
        }
    }
}

console.log(person.speak()()) //我的名字是bom,今年18岁