码迷,mamicode.com
首页 > 其他好文 > 详细

TS学习之函数

时间:2017-10-27 15:45:36      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:ast   fun   必须   argument   学习   color   箭头   erro   函数   

定义函数类型(规定函数参数及函数返回值的类型,若函数没有返回值,则返回类型为null)

function add(x: number, y: number): number {
    return x + y
}

推断类型(ts自动识别类型(按上下文归类))

function add(x: number, y: number) {
    return x + y
}
//ts会自动识别出返回类型为number

可选参数,默认参数,剩余参数

  • 可选参数(参数名旁使用 ?实现可选参数的功能,可选参数放在必填参数之后)
function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}

let result1 = buildName("Bob");  // Bob
let result3 = buildName("Bob", "Adams");  // Bob Adams
  • 默认参数(默认参数可传值也可不传,一般默认参数在必须参数之后,但也可以定义在默认参数之前,但此时必须明确传入undefined以获取默认值)
function buildName(firstName: string, lastName: string = "Smith") {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");  // Bob Smith
let result3 = buildName("Bob", "Adams");  // Bob Adams
function buildName(firstName: string = "Mr", lastName: string ) {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob","Adams");  // Bob Adams
let result2 = buildName("Bob"); //error: Expected 2 arguments, but got 1.
let result3 = buildName(undefined,"Smith")  //Mr Smith
  • 剩余参数(当参数个数不确定时)
function buildName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
console.log(employeeName)   //Joseph Samuel Lucas MacKinzie

this和箭头函数(传统函数的this作用域是在函数调用时确定,但箭头函数的this作用域在创建时就已经确定)

  • 传统函数
let myobj = {
    person:["Bob","Fred","Smith"],
    myFn:function(){
        return this.person
    }
}

let test = myobj.myFn;
console.log(test()) //undefined
  • 箭头函数
let myobj = {
    person: ["Bob", "Fred", "Smith"],
    myFn: function () {
        return () => {
           return this.person
        }
    }
}

let test = myobj.myFn();
console.log(test()) //[ ‘Bob‘, ‘Fred‘, ‘Smith‘ ]

TS学习之函数

标签:ast   fun   必须   argument   学习   color   箭头   erro   函数   

原文地址:http://www.cnblogs.com/sghy/p/7742785.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!