TypeScript lambda
lambda表达式 ()=>{something}或()=>something 相当于js中的函数,它的好处是可以自动将函数中的this附加到上下文中。
尝试执行以下:
- var shape = {
- name: "rectangle",
- popup: function() {
- console.log('This inside popup(): ' + this.name);
- setTimeout(function() {
- console.log('This inside setTimeout(): ' + this.name);
- console.log("I'm a " + this.name + "!");
- }, 3000);
- }
- };
- shape.popup();
实例中的 this.name 是一个空值:

接下来我们使用 TypeScript 的箭头函数。把 function() 替换为 () =>:
- var shape = {
- name: "rectangle",
- popup: function() {
- console.log('This inside popup(): ' + this.name);
- setTimeout( () => {
- console.log('This inside setTimeout(): ' + this.name);
- console.log("I'm a " + this.name + "!");
- }, 3000);
- }
- };
- shape.popup();
输出结果如下:

在以上实例编译后端 js 文件中,我们可以看到一行 var _this = this;,_this 在 setTimeout() 的回调函数引用了 name 属性。
转载本站内容时,请务必注明来自W3xue,违者必究。