typescript 函數

//typescript的函數定義和java十分類似,有點不同的地方在於:
//1、可以定義匿名函數
//2、可以以變量名的方式傳遞函數的引用地址
//3、直接使用lambda表達式定義匿名函數
//4、可能還有其他不同點,待發掘


//最正常的方式定義函數
function myfuntion(): void {
    console.log("最正統的函數定義方式");
}
myfuntion();//進行函數調用

//傳遞函數的引用地址,來“定義”新的函數
var myfuntion2 = myfuntion;
myfuntion2();

//定義匿名函數
var myfuntion3 = function () {
    console.log("使用function(){......}的方式定義匿名函數");
}
myfuntion3();

//定義匿名函數並使用,前端裏面經常這麼用!!!
(function () {
    console.log("定義匿名函數並立即使用!一次性的函數常這麼定義使用!")
})();

//使用lambda表達式定義函數
var myfuntion4 = () => {
    console.log("使用lambda表達式定義函數並傳遞的地址給某一個變量")
};
myfuntion4();

//入參可以像Java一樣不定長,同樣的必必須放在入參的最後一個
//並且,在函數內部使用時作爲的數組來使用
function myfuntion5(firstName: string, ...restName: string[]) {
    console.log(`first name is ${firstName} and restName is ${restName.join(" ")}`);
}
myfuntion5("chan");
myfuntion5("chan", "123", "6666");

//入參可以包含默認參數
//默認參數也是可以不輸入的,是一種特殊的可選參數的處理邏輯
function myfuntion6(firstName: string, secondName: string = "default string") {
    console.log(`first name is ${firstName} and second name is ${secondName} by default`);
}
myfuntion6("chan");

//入參包含可選參數
function myfuntion7(firstName?: string) {
    if (firstName) {
        console.log(`input arg is ${firstName}`);
    } else {
        console.log("no input arg");
    }
}
myfuntion7();
myfuntion7("chan");

//
var test_value;
//變量已聲明且時any類型,未賦值,爲undefined,也可以作爲condition判斷條件
if (test_value) {
    console.log(true);
} else {
    console.log(false);
}

test_value = ""
//賦值之後,字符串雖然已經有值,但是,值並不是爲true,所以還是打印false
if (test_value) {
    console.log(true);
} else {
    console.log(false);
}

/*
編譯輸出:
PS C:\CRroot\documents\codeproject\tampermonkey-scriptps> tsc .\typescript函數.ts;node
.\typescript函數.js
最正統的函數定義方式
最正統的函數定義方式
使用function(){......}的方式定義匿名函數
定義匿名函數並立即使用!一次性的函數常這麼定義使用!
使用lambda表達式定義函數並傳遞的地址給某一個變量
first name is chan and restName is
first name is chan and restName is 123 6666
first name is chan and second name is default string by default
no input arg
input arg is chan
false
false
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章