【问题标题】:How to save variable state with closure如何使用闭包保存变量状态
【发布时间】:2017-09-12 12:05:35
【问题描述】:

我有一个需要多次调用的函数,这个函数会在我的 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);
      }
    }
  }

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

谢谢。

【问题讨论】:

  • 第二个代码sn-pt更差!您仍然在每次调用时都获取父亲并定义一个实际上没有任何改进的函数!

标签: javascript node.js closures


【解决方案1】:

如果你使用 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);

【讨论】:

    【解决方案2】:

    最好的方法是将父亲声明为类的属性并在构造函数中获取一次,如下所示:

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

    但在这种情况下,_father 成员将是公众的。如果你想将它隐藏在闭包中,你必须在定义类方法时使用 IIFE(立即调用函数表达式),但由于 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);
            }
        }
    }());
    

    【讨论】:

    • 我可以像 MyClass.prototype = { somefunc() { /* 闭包 */ } } 一样使用吗?
    • 然后你必须提供构造函数和其他方法,这样你就不需要 ES 的 Class 文字语法,因为你必须重新定义类! 我认为
    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 2018-05-06
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多