【typescript基础篇】(第三章) 函数

函数

函数是JavaScript应用程序的基础。 它帮助你实现抽象层,模拟类,信息隐藏和模块。 在TypeScript里,虽然已经支持类,命名空间和模块,但函数仍然是主要的定义 行为的地方。 TypeScript为JavaScript函数添加了额外的功能,让我们可以更容易地使用

函数的基本使用

typescript 复制代码
// 匿名函数
const makeMoney = function(salary: number, reward: number): number {
  return salary + reward
}


// 有名函数 | 命名函数 | 普通函数
function writeCode(hour: number, sleep: number) {
  return hour
}
 

// 箭头函数
const seeMeiMei = (time: number):void => {
  console.log(`我每天要看${time}个小时MeiMei`);
  
}

seeMeiMei(8)


// 接口函数
type myFunc = (x: number, y: number) => number

const myfunc:myFunc = (a: number, b: number) => a + b

函数参数的处理

  • 可选参数:

    在 TypeScript 函数里,如果我们定义了参数,则我们必须传入这些参数,除非将这些参数设置为可选,可选参数使用问号标识

  • 默认参数:

    我们也可以设置参数的默认值,这样在调用函数的时候,如果不传入该参数的值,则使用默认参数,语法格式为:

    ts 复制代码
    function function_name(param1[:type],param2[:type] = default_value) { 
    }
  • 剩余参数:

    有一种情况,我们不知道要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义。

    剩余参数语法允许我们将一个不确定数量的参数作为一个数组传入。...args:any[]

typescript 复制代码
// 可选参数
const func1:(x: number, y?: number)=>number = function(a, b) {
  return a;
}


const func2 = function(a: number, b?: number): number {
  return a;
}

func2(10);
func2(10, 20);
func2(10, undefined);


// 函数的默认值
const func3 = function(a: number = 1, b:number =2, c:number=3) {
  return a + b + c;
}

func3();
func3(10);
func3(10, 20);
func3(10, 20, 30);


// 函数的剩余参数
const func4 = function(...args:any[]) {
  console.log(args);
  
}

func4(10, 20 , 30, "邱淑贞");

const func5 = function(a:number, b:number, ...args:any[]) {
  console.log(a);
  console.log(b);
  console.log(args);
  
}

func5(10, 20 , 30, "邱淑贞", "邢菲");

构造函数

TypeScript 也支持使用 JavaScript 内置的构造函数 Function() 来定义函数:

语法格式如下:

typescript 复制代码
var res = new Function ([arg1[, arg2[, ...argN]],] functionBody)

参数说明:

  • arg1, arg2, ... argN:参数列表
  • functionBody:一个含有包括函数定义的 JavaScript 语句的字符串。
typescript 复制代码
// 构造函数
var myFunction = new Function("a", "b", "return a * b"); 
var x = myFunction(4, 3); 
console.log(x);


// 递归函数
function sum(arr: number[], n: number):number {
  if(n <= 0){
    return 0;
  }else {
    return sum(arr, n-1) + arr[n-1];
  }
}

sum([2, 3, 4, 5], 3)

函数重载

重载是方法名字相同,而参数不同,返回类型可以相同也可以不同。

每个重载的方法(或者构造函数)都必须有一个独一无二的参数类型列表。

参数类型不同:

ts 复制代码
function disp(string):void; 
function disp(number):void;

参数数量不同:

ts 复制代码
function disp(n1:number):void; 
function disp(x:number,y:number):void;

参数类型顺序不同:

ts 复制代码
function disp(n1:number,s1:string):void; 
function disp(s:string,n:number):void;

如果参数类型不同,则参数类型应设置为 any

参数数量不同你可以将不同的参数设置为可选。

typescript 复制代码
// 不使用函数重载的问题
function add(a: number, b: number){
  return a + b;
}

add(10, 20);


function add2(a: string, b: string){
  return a + b;
}

add2("我的女神是: ", "邱淑贞");



function add3(a: string| number, b: string | number){
  // return a + b;
  if( typeof a=="number" && typeof b=="number"){
    return a + b;
  }
  if( typeof a=="string" && typeof b=="string"){
    return a + b;
  }
  if( typeof a=="string" && typeof b=="number"){
    return a + b;
  }
  if( typeof a=="number" && typeof b=="string"){
    return a + b;
  }
}

add3("我的女神是: ", "邱淑贞");
add3(10, 20);
add3("邱淑贞", 20);


// 定义函数重载
function addFunc(a:number, b: number):number;
function addFunc(a:string, b: string):string;
function addFunc(a:number, b: string):string;
function addFunc(a:string, b: number):string;


// 使用函数重载
function addFunc(a: any, b: any):any {
  return a + b;
}
addFunc(10, 20);
addFunc("谭松韵", "金晨");
addFunc(27, "白鹿");
addFunc("赵今麦", 19);


// 定义参数类型与参数数量不同
function star(s1:string):void; 
function star(n1:number,s1:string):void; 
 
function star(x:any,y?:any):void { 
    console.log(x); 
    console.log(y); 
} 
star("王心凌"); 
star(1,"爱你");

this的使用

  • JavaScript里,this的值在函数被调用的时候才会指定。 这是个既强大又灵活的特点,但是你需要花点时间弄清楚函数调用的上下文是什么。 但众所周知,这不是一件很简单的事,尤其是在返回一个函数或将函数当做参数传递的时候。
  • 从 TypeScript 2.0 开始,在函数和方法中我们可以声明 this 的类型,实际使用起来也很简单
typescript 复制代码
let userInfo = {
  name: "邱淑贞",
  age: 18,
  song: "恨你太无情",
  marry: true,
  show: function () {
    this.marry = false;
  },
};



class Rectangle1 {
  private w: number;
  private h: number;

  constructor(w: number, h: number) {
    this.w = w;
    this.h = h;
  }

  getArea() {
    return () => {
      return this.w * this.h;
    };
  }
}

class Rectangle2 {
  private w: number;
  private h: number;

  constructor(w: number, h: number) {
    this.w = w;
    this.h = h;
  }

  getArea(this: Rectangle2) {
    return () => {
      return this.w * this.h;
    };
  }
}

// class Rectangle3 {
//   private w: number;
//   private h: number;

//   constructor(w: number, h: number) {
//     this.w = w;
//     this.h = h;
//   }

//   getArea(this: void) {
//     return () => {
//       return this.w * this.h;
//     };
//   }
// }

特殊的函数返回值

  • 如果使用类型别名,定义了一个返回值为void的类型, 我们在函数使用的时候,并非一定不能有返回值。

    相反,如果我们在函数中写了返回值,我们的返回值是有效的。

  • 如果我们定义函数的时候明确指出,返回值为void,那么我们将除undefined 和 null 以外的值进行返回都会进行报错

typescript 复制代码
type voidFunc = () => void


let func1: voidFunc = function() {
  return true;
}


let func2: voidFunc = () => {
  return false;
}

let f1 = func1();
let f2 = func2();
console.log("f1: ", f1);
console.log("f2: ", f2);



// 注意点: 如果我们定义函数的时候明确指出,返回值为void,
// 那么我们将除undefined 和 null 以外的值进行返回


function func3():void {
  // return 123 // 报错
}
相关推荐
崔庆才丨静觅4 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60615 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了5 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅5 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅5 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅6 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅6 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊6 小时前
jwt介绍
前端
爱敲代码的小鱼6 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax