调用功能超出范围 [英] Invoking function breaks scope

查看:79
本文介绍了调用功能超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此处相同的问题: AngularJS指令将具有多个参数的函数绑定在一起

遵循此答案: https://stackoverflow.com/a/26244600/2892106

尽我所能.

这有效:

<my-directive on-save="ctrl.saveFn"></my-directive>

使用:

angular.module('app')
.controller('MyController', function($scope) {
  var vm = this;
  vm.saveFn = function(value) { vm.doSomethingWithValue(value); }
});

但是当我转换为Typescript并使用实型类时,这会中断.

But when I convert to Typescript and use real classes, this breaks.

class MyController {
  constructor() {}

  saveFn(value) {
    this.doSomethingWithValue(value);
  }
}

在调试时的Typescript版本中,"this"是引用Window全局的.因此,我的范围被某种方式弄乱了,但我不知道如何解决.如何获得"this"以按预期引用MyController?

In the Typescript version when debugging, "this" is referencing the Window global. So my scope is messed up somehow, but I don't know how to fix it. How can I get "this" to refer to MyController as expected?

推荐答案

所以我的范围被弄乱了

So my scope is messed up somehow

使用箭头函数代替方法.

Use an arrow function instead of a method.

class MyController {
  constructor() {}

  saveFn = (value) => {
    this.doSomethingWithValue(value);
  }
}

更多

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

这篇关于调用功能超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆