函数定义
//ES5函数声明
function fn(){
return 1;
}
//ES5匿名函数
let fun = function(){
return 0;
};
//TS定义函数
function func():number{
return 0;
}
let fnc = function():number{
return 1;
};
//TS定义函数传参
function getInfo(id:number):string{
return `id = ${id}`;
}
console.log(getInfo(1));//id = 1
let getInfo = function(id:number):string{
return `id = ${id}`;
};
console.log(getInfo(1));
定义没有返回值的方法
function log(msg:string):void{
console.log(`message:${msg}`);
}
log("hello world");//message:hello world
可选参数
- ES5中方法的实参和形参可以不一样,但TS中必须一样,如果不一样就需要配置可选参数。
function getInfo(id:number, name?:string):string{
return `id = ${id} name = ${name}`;
}
console.log(getInfo(1));//id = 1 name = undefined
console.log(getInfo(1, "junchow"));//id = 1 name = junchow
- 可选参数必须配置到参数的后面
function getInfo(id?:number, name:string):string{
return `id = ${id} name = ${name}`;
}
//app.ts(1,30): error TS1016: A required parameter cannot follow an optional parameter.
// app.ts(4,13): error TS2554: Expected 2 arguments, but got 1.
console.log(getInfo(1));
console.log(getInfo(1, "junchow"));
默认参数
- ES5中无法设置默认参数,ES6和TS中都可以设置默认参数。
function getInfo(id?:number, name:string="guest"):string{
return `id = ${id} name = ${name}`;
}
console.log(getInfo(1));//id = 1 name = guest
console.log(getInfo(1, "junchow"));//id = 1 name = junchow
剩余参数
function sum(...params:number[]):number{
let result = 0;
for(let i=0; i<params.length; i++){
result += params[i];
}
return result;
}
console.log(sum(1,2,3,4));//10
console.log(sum(1,2,3,4,5));//15
function sum(x:number, y:number, ...params:number[]):number{
let result = x + ;
for(let i=0; i<params.length; i++){
result += params[i];
}
return result;
}
console.log(sum(1,2,3,4));//10
console.log(sum(1,2,3,4,5));//15
函数重载
Java中方法重载是指 两个或多个参数不同的同名函数存在时即发生函数重载。
TypeScript中函数重载是指通过为同一个函数提供多个函数类型定义多种功能。
TS为了兼容ES5和ES6,重载写法和Java有所不同。
//ES5中同名函数后者会替换前者
function css(cfg:any):any{
}
function css(cfg:any, val:any):any{
}
TS中方法重载,定义函数时没有函数体
function getInfo(id:number):string;
function getInfo(name:string):string;
function getInfo(tmp:any):any{
if(typeof tmp === "string"){
return `name = ${tmp}`;
}else{
return `id = ${tmp}`;
}
}
console.log(getInfo(1));//id = 1
console.log(getInfo("junchow"));//name = junchow
function getInfo(name:string):string;
function getInfo(name:string, id:number):string;
function getInfo(name:any, id?:any):any{
if(id){
return `id = ${id} name = ${name}`;
}else{
return `name = ${name}`;
}
}
console.log(getInfo("junchow"));//name = junchow
console.log(getInfo("junchow", 1));//id = 1 name = junchow
箭头函数ES6
//ES5
setTimeout(function(){
console.log("run");
}, 1000);
//ES6
setTimeout(()=>{
console.log("arrow");
}, 1000);
箭头函数中的this
指向上下文