在同一方法中使用函数参数

时间:2016-02-01 14:16:59

标签: typescript

我在JavaScript中有一个函数,它使用this并捕获参数:

var Watcher = function() {
  var callbacks = [];
  var currentValue = null;

  this.watch = function (callback) {
    callbacks.push(callback);
    if (currentValue) {
      callback.apply(null, currentValue);
    }
  };
  this.notify = function() {
    currentValue = arguments;
    for (var i = 0; i < callbacks.length; i++) {
      callbacks[i].apply(null, arguments);
    }
  };
}

我想将其更改为TypeScript类。我想出的是:

class Watcher {
  private currentValue: any[] = null;
  private callbacks: Function[] = [];

  watch = (callback: Function) => {
    this.callbacks.push(callback);
    if (this.currentValue) {
      callback.apply(null, this.currentValue);
    }
  }
  // cannot access arguments
  notify = () => {
    this.currentValue = /*arguments?*/;
    for (var callback of this.callbacks) {
      callback.apply(null, /*arguments?*/);
    }
  }
  // cannot acces this
  notify() {
    /*this?*/.currentValue = arguments;
    for (var callback of /*this?*/.callbacks) {
      callback.apply(null, arguments);
    }
  }
}

如何创建一个函数,我可以使用this引用来访问我的字段,传递给我的函数的参数?

1 个答案:

答案 0 :(得分:2)

您可以使用箭头函数执行此操作,该函数使用"Rest" parameter来捕获无数个可选参数:

notify = (...args) => {
  this.currentValue = args;
  for (var callback of this.callbacks) {
    callback.apply(null, args);
  }
}