课程表

TypeScript课程

工具箱
速查手册

TypeScript lambda

当前位置:免费教程 » JS/JS库/框架 » TypeScript

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

尝试执行以下:

  1. var shape = {
  2. name: "rectangle",
  3. popup: function() {
  4. console.log('This inside popup(): ' + this.name);
  5. setTimeout(function() {
  6. console.log('This inside setTimeout(): ' + this.name);
  7. console.log("I'm a " + this.name + "!");
  8. }, 3000);
  9. }
  10. };
  11. shape.popup();

实例中的 this.name 是一个空值:

显示空值

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

  1. var shape = {
  2. name: "rectangle",
  3. popup: function() {
  4. console.log('This inside popup(): ' + this.name);
  5. setTimeout( () => {
  6. console.log('This inside setTimeout(): ' + this.name);
  7. console.log("I'm a " + this.name + "!");
  8. }, 3000);
  9. }
  10. };
  11. shape.popup();

输出结果如下:

输出结果

在以上实例编译后端 js 文件中,我们可以看到一行 var _this = this;,_this 在 setTimeout() 的回调函数引用了 name 属性。

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号