任何节约和储蓄的方式在打字稿中使用这个上下文?

时间:2016-03-11 06:38:08

标签: typescript

我有一个现有的angular 1.4应用程序,我想移植到打字稿。 假设我有以下的typescript类:

class my {
  constructor(public msg: string) {     
  }

  a() {
    alert(this.msg);
  }
}

我希望下面的两个调用都做同样的事情:

var a = new my('hello');
a.a();
var fn = a.a;
fn();

然而,fn不起作用,它失去了它的范围。我知道我可以使用胖箭头语法(a = () => {})来保存单个方法的范围。

我想要一个更优雅的解决方案,将此范围保存在变量中并始终可以访问它,而不必使用胖箭头声明我的每个方法。

更新:对不起,我要找的是一个打字稿类,它将输出以下Javascipt(注意_self变量及其用法):

 var my = (function () {
  var self = this;
  function my(msg) {
    self.msg = msg;
  }
  my.prototype.a = function () {
    alert(self.msg);
  };
  return my;
}());

1 个答案:

答案 0 :(得分:1)

您可以使用bind

var instance = new my('hello');
instance.a(); // Call instance method
var fn = instance.a.bind(instance); // Get bound method
fn(); // Call bound method

更新1。

您如何使用该方法从类中获取绑定方法:

function getBoundMethod(instance, methodName) {
    return instance[methodName].bind(instance);
}

var instance = new my('hello');
instance.a(); // Call instance method
var fn = getBoundMethod(instance, "a"); // Get bound method
fn(); // Call bound method