我有一个需要多次调用的函数,该函数将在我的 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
成员将是公开的。如果你想将它隐藏在闭包中,则必须在定义类方法时使用IIFE(立即调用函数表达式),但由于 ES 类文字不允许 IIFE,因此你必须使用旧原型(prototype),如下所示:
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);
}
}
}());
关于javascript - 如何用闭包保存变量状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441868/