如何用闭包保存variables状态

我有一个函数,我需要调用几次,这个函数将追加我的HTML元素:

class MyClass { somefunct(elements) { const father = $("#father").find("#other-element"); for (let element of elements) { father.append(element); } } } 

我想避免在每次通话中初始化父亲。 怎么会这样?

我在做什么:

  somefunct(elements) { const father = $("#father").find("#other-element"); this.somefunc = (elements) => { for (let element of elements) { father.append(element); } } } 

这将会起作用,但我不知道这是否是一种不好的做法,或者是否有更好的方法。

谢谢。

最好的方法是将父类声明为类的属性,然后像下面这样在构造函数中获取它:

 class MyClass { constructor() { this._father = $("#father").find("#other-element"); } somefunct(elements) { for (let element of elements) { this._father.append(element); } } } 

但在这种情况下, _father成员将是_father 。 如果你想把它隐藏在闭包中,你必须在定义类方法时使用IIFE (立即调用的函数expression式),但是由于ES类文字不允许IIFE,所以你必须使用这样的旧原型:

 class MyClass { // ... other methods } MyClass.prototype.somefunct = (function() { const father = $("#father").find("#other-element"); return function(elements) { for (let element of elements) { father.append(element); } } }()); 

如果你使用ES6类。 这可以这样做:

  class MyClass { constructor(options){ this.$father = options.el; } somefunct(elements) { for (let element of elements) { this.$father.append(element); } } } let classInstance = new MyClass({ el: $("#father").find("#other-element") }); classInstance.somefunct(elements);