一、使用环境

Mac 电脑

WebStorm

TypeScript3.x版本

二、基本函数

2.1、函数声明定义

function sum(x : number, y : number) : number {
return x + y;
}
console.log(sum(2,4));

2.2、函数表达式定义

let mySum = function (x: number, y: number): number {
return x + y;
};

2.3、用接口定义函数

interface ISearchFunc {
(source : string, substring : string):boolean;
};
let searchfunc : ISearchFunc;
searchfunc = function (source : string, substring : string) {
return source.search(substring) != -1;
};
console.log(searchfunc("2334455",'45'));

2.4、函数参数:可选参数 和默认值参数

// 可选参数后面不允许再出现必须参数了
// 默认参数:默认值的参数识别为可选参数
// ...rest 的方式获取函数中的剩余参数 字符串数组
function buildName( firstName:string, lastName?:string, age : number = 10,...items:string[]) {
console.log(items);
if(lastName){
return firstName + '加上' + lastName + '数字' + age.toString();
}else {
return firstName + age.toString();
}
}
console.log((buildName("tom","455",23,'5',"45","法国队和规范")));

三、箭头函数

3.1、基本语法

ES6 允许使用“箭头”(=>)定义函数

箭头函数相当于匿名函数,并且简化了函数定义

表现形式一:包含一个表达式,连{ ... }和return都省略掉了

x => x * x //包含一个表达式,连{ ... }和return都省略掉了

等同于

function (v) {
return v;
};

表示形式二:包含多条语句,这时候就不能省略{ ... }和return

x => { // 包含多条语句,这时候就不能省略{ ... }和return
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}

基础语法

A、(参数1, 参数2, …, 参数N) => { 函数声明 }

B、(参数1, 参数2, …, 参数N) => 表达式(单一)

//相当于:(参数1, 参数2, …, 参数N) =>{ return 表达式; }

// 当只有一个参数时,圆括号是可选的:

C、(单一参数) => {函数声明}

D、单一参数 => {函数声明}

// 没有参数的函数应该写成一对圆括号。

E、() => {函数声明}

3.2、高级语法

A、加括号的函数体返回对象字面表达式:

参数=> ({foo: bar})

B、支持剩余参数和默认参数

(参数1, 参数2, ...rest) => {函数声明}

(参数1 = 默认值1,参数2, …, 参数N = 默认值N) => {函数声明}

C、同样支持参数列表解构

let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6

3.3、箭头函数的this

箭头函数的引入有两个方面的作用:

一是更简短的函数书写

二是对this的词法解析。

普通函数: this指向调用它的那个对象

箭头函数:不绑定this,会捕获其所在的上下文的this值,作为自己的this值,任何方法都改变不了其指向,如 call() , bind() , apply()

var obj = {
a: 10,
b: () => {
console.log(this.a); // undefined
console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
},
c: function() {
console.log(this.a); // 10
console.log(this); // {a: 10, b: ƒ, c: ƒ}
}
}
obj.b();
obj.c();

由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向

3.3、箭头函数的其他属性方法

普通函数存在的 arguments、super、new、target、yield、prototype在箭头函数中不存在

function foo() {
setTimeout(() => {
console.log('args:', arguments);
}, 100);
}
foo(2, 4, 6, 8)

上面代码中,箭头函数内部的变量arguments,其实是函数foo的arguments变量

箭头函数有几个使用注意点。

(1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

(2)不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

(3)不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。

(4)不可以使用yield命令,因此箭头函数不能用作 Generator 函数。