函数是JavaScript应用程序的基础。它帮助你实现抽象层,模拟类,信息隐藏和模块。在TypeScript里,虽然已经支持类,命名空间和模块,但函数仍然是主要的定义行为的地方。TypeScript为JavaScript函数添加了额外的功能,让我们可以更容易地使用
- export default {}
- // 匿名函数
- const sum1=function(a:number,b:number):number{
- return a+b
- }
- let res1=sum1(45,98)
- console.log(res1);
-
- // 有名函数 | 命名函数 | 普通函数
- function sum2(x:number,y:number):number{
- return x
- }
- let res2=sum2(1,2)
- console.log(res2);
-
- // 箭头函数
- const seeTv=(time:number):void => {
- console.log(`我每天看电视剧${time}个小时`);
- }
- seeTv(2)
- // 简写
- // const seeTv=(time:number):void => console.log(`我每天看电视剧${time}个小时`);
-
- // 接口函数
- // type 定义别名
- type myFun=(x1:number,y1:number) => number
- let myfun:myFun=(c:number,d:number) => c+d
在TypeScript函数里,如果我们定义了参数,则我们必须传入这些参数,除非将这些参数设置为可选,可选参数使用问号标识?
我们也可以设置参数的默认值,这样在调用函数的时候,如果不传入该参数的值,则使用默认参数,语法格式为``
function function_name(param1[:type] , param2[:type] = default_value){}
有一种情况,我们不知道要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义。剩余参数语法允许我们将一个不确定数量的参数作为一个数组传入。...args:any[]
- export default {}
- // 可选参数
- const fun1:(x:number,y?:number)=>number=(a:number,b?:number)=>{
- return a
- }
- let res1=fun1(10,20);
- console.log(res1);
-
- const fun2:(x:number,y?:number)=>number=function(a,b){
- return a
- }
-
- const fun3=function(a:number,b?:number){
- return a
- }
- fun3(10)
- fun3(10,20)
- fun3(10,undefined)
- // console.log(fun3);
-
- // 参数的默认值
- const fun4=function(a:number,b:number,c:number=3){
- return a+b+c
- }
- fun4(1,2)//1,2,3
- fun4(12,65,84)//12,65,84
-
- const fun5=function(a:number=100,b:number=200,c:number=300){
- return a+b+c
- }
- fun5()//100,200,300
- fun5(1,2)//1,2,300
-
- // 函数的剩余参数
- const fun6=function(...rest:any[]){
- console.log(rest);
- }
- fun6('杨幂',10,true)
-
- const fun7=function(a:number,b:string,...rest:any[]){
- console.log(a);
- console.log(b);
- console.log(rest);
- }
- fun7(10,'杨幂',true,'迪丽热巴',18)
TypeScript 也支持使用JavaScript内置的构造函数 Function()来定义函数:
语法格式如下:
var res = new Function ([arg1[,arg2[,...argN]],] functionBody)
参数说明:
- arg1, arg2, ... argN:参数列表
- functionBody:一个含有包括函数定义的JavaScript 语句的字符串。
- export default {}
-
- // 构造函数
- var myfun=new Function('a','b','return a*b');
- console.log(myfun(10,20));
重载是巧法名字相同,而参数不同,返回类型可以相同也可以不同。
每个重载的方法(或者构造函数〕都必须有一个独一无二的参数类型列表。
参数类型不同:
- function disp(string) :void;
- function disp (number) : void;
参数数量不同:
- function disp(n:number) : void;
- function disp(x:number , y:number): void;
参数类型顺序不同:
- function disp(n: number ,s;string): void;
- function disp(s :string,n : number : void;
如果参数类型不同,则参数类型应设置为any
参数数呈不同你可以将不同的参数设置为可选。
- export default {}
-
- // 不使用函数重载的问题
- function add1(a:number,b:number){
- return a+b
- }
- add1(10,20)
- function add2(a:string,b:string){
- return a+b
- }
- add2('我的名字叫做:','迪丽热巴')
-
- function add3(a:string|number,b:string|number){
- if(typeof a =='number' && typeof b =='number'){
- return a+b
- }else if(typeof a =='string' && typeof b =='string'){
- return a+b
- }else if(typeof a =='number' && typeof b =='string'){
- return a+b
- }else if(typeof a =='string' && typeof b =='number'){
- return a+b
- }
- }
- add3('我的名字叫做:','迪丽热巴')
- add3(10,15)
- add3(10,'杨幂')
- add3('白鹿',19)
-
- // 定义函数重载
- function addFun(a:number,b:number):number;
- function addFun(a:string,b:string):string;
- function addFun(a:string,b:number):string;
- function addFun(a:number,b:string):string;
- // 使用函数重载
- function addFun(a:any,b:any):any{
- return a+b
- }
- addFun(10,20)
- addFun('我的名字叫做:','迪丽热巴')
- addFun('蔡徐坤',20)
- addFun(10,'赵金麦')
-
- // 定义参数类型与参数数量不同
- function star(a:string):string
- function star(a:number,b:string):void
- function star(a:any,b?:any):any{
- console.log(a+b);
- }
- star('杨幂')
- star(12,'白鹿')
- // star(10)
定义:
TypeScript类定义方式如下: class class_name {}
定义类的关键字为class,后面紧跟类名,类可以包含以下几个模块((类的数据成员)∶
- export default {}
-
- class Person{
- // name:string='杨幂'//初始化表达式
- // 注意点:需要先定义实例属性,才能使用
- // 字段(属性)
- name:string
- age:number
- // 构造函数
- constructor(name:string,age:number){
- // this指的是外面的name与age
- this.name=name
- this.age=age
- }
- // 函数(方法)
- sayHello():void{
- console.log(`我叫${this.name},今天${this.age}岁了`);
- }
- }
- let p = new Person('赵金麦',21)
- p.sayHello()
TypeScript支持继承类,即我们可以在创建类的时候继承一个已存在的类,这个已存在的类称为少类,继承它的类称为了类。
类继承使用关键字extends,子类除了不能继承父类的私有成员(方法和属性)和构造函数,其他的都可以继承。
Typescript一次只能继承一个类,不支持继承多个类,但TypeScript支持多重继承(A继承B,B继承C)。
语法格式如下:c1ass child_class_name extends parent_class_name
- export default {}
-
- class Person{
- // 字段(属性)
- name:string
- age:number
- // 构造函数
- constructor(name:string,age:number){
- this.name=name
- this.age=age
- }
- // 函数(方法)
- sayHello():void{
- console.log(`我的女神是${this.name},她今年${this.age}岁了,在我心中她永远18岁!`);
- }
- }
- // extends 继承
- class Student extends Person{
- score:string
- constructor(name:string,age:number,score:string){
- // 调用父级中的构造函数
- super(name,age)
- this.score=score
- }
- sayHello(): void {
- // 调用父级的函数
- super.sayHello()
- console.log(`我是重写之后的,我叫${this.name},今年${this.age}岁了,我的成绩是${this.score}等级`);
- }
- }
- let p = new Student('鞠婧祎',18,'A')
- p.sayHello()
- export default {}
- // static 关键字用于定义类的数据成员(属性和方法)为静态的,静态成员可以直接通过类名调用。
- class StaticTest{
- static salary:number
- static say():void{
- console.log(`我们想要的工资是:${StaticTest.salary}k`);
-
- }
- }
- StaticTest.salary=18
- StaticTest.say()
-
- // instanceof运算符用于判断对象是否是指定的类型,如果是返回true,否则返回false。
- class Person{}
- let p = new Person()
- let isPerson = p instanceof Person
- console.log(`p 对象是 Person 类实例化来的吗?${isPerson}`);//true
-
- // 继承
- class Student extends Person{}
- let s = new Person()
- let isStudent = s instanceof Person
- console.log(`s 对象是 Person 类实例化来的吗?${isStudent}`);//true
- export default {}
-
- /**
- * public(默认):公有,可以在任何地方被访问
- * protected:受保护,可以被其自身以及其子类访问
- * private:私有,只能被其定义所在的类访问
- * readonly:可以使用readonly关键字将属性设置为只读的。只读属性必须在声明时或构造函数里被初始化。
- */
- class Person{
- public name:string
- protected age:number
- private sex:string
- constructor(name:string,age:number,sex:string){
- this.name = name
- this.age = age
- this.sex = sex
- }
- say():void{
- console.log(`我的名字是${this.name},性别为${this.sex},今年${this.age}岁了`);
- }
- }
-
- class Student extends Person{
- score:string
- constructor(name:string,age:number,sex:string,score:string){
- super(name,age,sex)
- this.score = score
- }
- say():void{
- console.log(this.name);
- console.log(this.age);
- // console.log(this.sex);//私有
- console.log(this.score);
- }
- }
- let s = new Student('林志颖',18,'男','A')
- s.say()
-
- // 只读 readonly
- class Print{
- readonly str1:string = 'HTML'
- readonly str2:string
- readonly str3:string
- readonly str4:string
- constructor(str1:string,str2:string,str3:string,str4:string){
- this.str2 = str2
- this.str3 = str3
- this.str4 = str4
- }
- // show():void{
- // this.str2='js'
- // }
- }
- let p = new Print('JavaScript','jQuery','Bootstrap','TypeScript')
- console.log(p);
官方的另外一个名字:存取器
通过getters/setlers来载取对对象成员的访问
注意点:
如果存在get ,但没有set ,则该属性自动是只读的
如果没有指定setter参数的类型,它将从getter的返回类型中推断出来
访问器和设置器必须有相同的成员可见性
- export default {}
-
- class MyName{
- private _fullName:string='白鹿'
- // 读取字段的值
- get fullName(){
- console.log('get被调用了');
- return this._fullName
- }
-
- // 为字段赋值
- set fullName(newName:string){
- console.log('set被调用了');
- this._fullName = newName
- }
- }
- let m = new MyName()
- m.fullName='虞书欣';//赋值
- console.log(m);
- console.log(m.fullName);//取值
- export default {}
-
- abstract class Person{
- abstract name:string
- abstract age:number
- abstract show():string
-
- showName():void{
- console.log('Hello World');
- }
- }
-
- class Student extends Person{
- name: string='杨颖'
- age:number=18
- show(){
- return '奔跑吧兄弟'
- }
- }
- // 抽象类不会被直接实例化
- // let p = new Person()
- let s = new Student()
- let res = s.show()
- console.log(res);
- export default {}
-
- class Old{
- name:string='李易峰'
- constructor(){
- console.log(`我是${this.name},我主演了古剑奇谭`);
- }
- }
- class Young extends Old{
- name: string='赵露思'
- constructor(){
- super()
- console.log(`我是${this.name},我主演了星汉灿烂`);
- }
- }
- let y = new Young()