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,可以看到如下打印信息:
接下来使用 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
;,_this
在 setTimeout()
的回调函数引用了 name
属性。
参考文档:
https://www.runoob.com/w3cnote/getting-started-with-typescript.html
https://www.runoob.com/typescript/ts-tutorial.html
https://www.tslang.cn/