函數(shù)在各個(gè)語言里用的太多了,就不贅述,只討論一下TypeScript的函數(shù)跟JS的函數(shù)不同的地方.
1.函數(shù)類型
TypeScript里的函數(shù)需要給參數(shù)和返回值都指定類型,它能夠根據(jù)返回語句,自動(dòng)判斷返回值類型,通常都可以省略
function add(x: number, y: number):number{
return x + y;
}
console.log(add(1, 2));
接下來看一下函數(shù)的完整類型,參數(shù)類型和返回值類型用=>隔開
let myAdd: (x:number, y:number)=>number =
function(x: number, y: number): number { return x+y; };
2.可選參數(shù)和默認(rèn)參數(shù)
當(dāng)參數(shù)可傳可不傳的時(shí)候,就可以在對應(yīng)的參數(shù)名旁邊加上?修飾,實(shí)現(xiàn)可選參數(shù)功能,如果沒傳值,對應(yīng)形參值是undefined.要把可選的參數(shù)放到參數(shù)最后面
function buildName(firstName: string, lastName?: string){
console.log(firstName + " " + lastName);
}
buildName("龍哥");
buildName("東旭", "龍哥");
默認(rèn)參數(shù)在ES6之后,JS的函數(shù)也能設(shè)置.
function buildName(firstName: string, lastName = "趙") {
return firstName + " " + lastName;
}
3.剩余參數(shù) Rest參數(shù)
這個(gè)也是ES6里新出現(xiàn)的特性,在JS里有一個(gè)非常重要的對象arguments,即使不寫形參,也可以通過arguments獲取到形參內(nèi)容.剩余參數(shù)會被當(dāng)做個(gè)數(shù)不限的可選參數(shù),可以一個(gè)都沒有,同樣也可以有任意個(gè).編譯器創(chuàng)建參數(shù)數(shù)組,名字是你在省略號( ... )后面給定的名字,你可以在函數(shù)體內(nèi)使用這個(gè)數(shù)組.
function buildName(firstName: string, ...restOfName: string[]) {
console.log(restOfName);
}
buildName("趙", "錢", "孫", "李");
4.this和箭頭函數(shù)
在JS里,this的使用對于很多初學(xué)者來說,會出很多問題,很多問題都出現(xiàn)在this的指向,如果真出問題,大家可以先打印一下this的指向,看一個(gè)例子
let deck = {
name: ["宋江", "盧俊義", "吳用", "公孫勝"],
test: function() {
return function() {
let num1 = Math.floor(Math.random() * 52);
let num2 = Math.floor(num1 / 13);
console.log(this.name);
return {suit: this.name[num2], card: num1 % 13}; }
}
}
let cardPicker = deck.test();
let pickedCard = cardPicker();
console.log(pickedCard);
這里打印出來suit的內(nèi)容是undefined,原因就是出現(xiàn)在this的問題,這里的this實(shí)際上指代的是window,因?yàn)閐eck是window的變量,window上沒有name的變量,所以當(dāng)取值的時(shí)候,就是undefined,還是this指向的問題.ES6里,可以使用箭頭函數(shù)來解決這種指代.箭頭函數(shù)能報(bào)錯(cuò)函數(shù)創(chuàng)建時(shí)候的this,而不是調(diào)用時(shí)候的this
let deck = {
name: ["宋江", "盧俊義", "吳用", "公孫勝"],
test: function() {
return ()=> {
let num1 = Math.floor(Math.random() * 52);
let num2 = Math.floor(num1 / 13);
console.log(this.name);
return {suit: this.name[num2], card: num1 % 13}; }
}
}
TypeScript里的對象,屬性都有對應(yīng)類型,可以在接口里設(shè)置this的類型,上述例子里的this對應(yīng)的都是any類型,通過類型也能避免指向問題
interface Deck {
suits: string[];
test(this: Deck)=>Deck;
}
let deck: Deck = {
suits:["宋江", "盧俊義", "吳用", "公孫勝"],
test: function(this: Deck) {
return () => {
let num1 = Math.floor(Math.random() * 52);
let num2 = Math.floor(num1 / 13);
return {suit: this.name[num2], card: num1 % 13};
}
}
}