如何为函数分配ES6类方法?

时间:2016-11-08 00:29:25

标签: javascript function methods ecmascript-6

有没有办法做类似

的事情
class AppContainer {
    fetch = _.debounce(...) {
    }
}

我需要将一个类方法别名为lodash debounce函数。

2 个答案:

答案 0 :(得分:1)

您可以单独定义方法,然后在构造函数中手动对其进行去抖动,如下所示:

class AppContainer {
  constructor(...args){
    super(...args);
    this.fetch = _.debounce(this.fetchImpl_.bind(this));
  }

  fetchImpl_(){

  }
}

答案 1 :(得分:0)

像往常一样将它添加到原型中。引用:

  

ECMAScript 6中引入的JavaScript类是JavaScript现有的基于原型的继承的语法糖

演示:

// Define a class using the pre ECMA-6 mechanism
function Wonk(n) {
    this.name = n;
}

// Add a function to the prototype of our pre ECMA-6 class
Wonk.prototype.wonk = function() { console.log( "Funky" ); };

// Create an instance of our pre ECMA-6 class as a stand-in for lodash's _
var wonk = new Wonk();

// Define an ECMA-6 class
class Funky {
    constructor() {
    }
}

// ECMA-6 class definition does not support (this claim needs a reference) adding a function by reference in the definition, so add it with the pre ECMA-6 mechanism
Funky.prototype.foo = wonk.wonk;

// Test the resulting class.
function init() {
    var funky = new Funky();
    funky.foo();
}

document.addEventListener("DOMContentLoaded", init, false);