0
点赞
收藏
分享

微信扫一扫

TypeScript 学习系列 —— 箭头函数表达式(lambda表达式)

西街小学的王 2022-04-02 阅读 146

TypeScript 箭头函数表达式(lambda表达式)

lambda表达式 ()=>{something}()=>something相当于 js 中的函数,好处是可以自动将函数中的 this 附加到上下文中。

实例

index.html 文件:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>typescript demo</title>
</head>
<body>
 	<script src="hello.js"></script>
</body>
</html>

hello.ts文件:

var student = {
  name: 'xiaoming',
  sayHi: function(){
    console.log('this is sayHi():' + this.name);
    setTimeout(function(){
    	console.log('this is setTimeout():' + this.name);
    },3000)
  }
}

student.sayHi()

接下来,打开命令行,使用 tsc 命令编译 hello.ts 文件:

$ tsc hello.ts

在相同目录下,会生成一个 hello.js 文件,此时项目结构:

  typescript-demo
  |- /src
    |- hello.js
    |- hello.ts

此时,hello.js文件如下:

var student = {
    name: 'xiaoming',
    sayHi: function () {
        console.log('this is sayHi():' + this.name);
        setTimeout(function () {
            console.log('this is setTimeout():' + this.name);
        }, 3000);
    }
};
student.sayHi();

然后,打开 index.html,可以看到如下打印信息:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JkkS8d7z-1646995173287)(:storage\6ep82jfm5g41v2t9.png)]

接下来使用 TypeScript 的箭头函数。把 function() 替换为 () =>

hello.ts文件:

var student = {
  name: 'xiaoming',
  sayHi: function(){
    console.log('this is sayHi():' + this.name);
    setTimeout(()=>{
    	console.log('this is setTimeout():' + this.name);
    },3000)
  }
}

student.sayHi()

打开命令行,使用 tsc 命令编译 hello.ts 文件:

$ tsc hello.ts

打开 index.html,可以看到如下打印信息:
在这里插入图片描述

此时,hello.js文件如下:

var student = {
    name: 'xiaoming',
    sayHi: function () {
        var _this = this;
        console.log('this is sayHi():' + this.name);
        setTimeout(function () {
            console.log('this is setTimeout():' + _this.name);
        }, 3000);
    }
};
student.sayHi();

可以看到,多了一行 var _this = this;,_thissetTimeout() 的回调函数引用了 name 属性。

参考文档:

https://www.runoob.com/w3cnote/getting-started-with-typescript.html
https://www.runoob.com/typescript/ts-tutorial.html
https://www.tslang.cn/

举报

相关推荐

0 条评论