Reputation:
I have a function that i need call several times, and this function will append elements in my html:
class MyClass {
somefunct(elements) {
const father = $("#father").find("#other-element");
for (let element of elements) {
father.append(element);
}
}
}
I would like to avoid call initialize the father in every call. How so?
How i'm doing:
somefunct(elements) {
const father = $("#father").find("#other-element");
this.somefunc = (elements) => {
for (let element of elements) {
father.append(element);
}
}
}
And this will work, but i don't know if this is a bad practice, or if there is a better approach.
Thank you.
Upvotes: 1
Views: 70
Reputation: 746
If you use ES6 classes. This can be done like this:
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);
Upvotes: 0
Reputation: 31712
The best way to do it is to declare the father as a property of the class and fetch it once in the constructor like this:
class MyClass {
constructor() {
this._father = $("#father").find("#other-element");
}
somefunct(elements) {
for (let element of elements) {
this._father.append(element);
}
}
}
But in this case the _father
member will be puplic. If you want to hide it in a closure, you must use an IIFE (Immediately Invoked Function Expression) while defining the class method, but since ES class literals don't allow IIFE, you'll have to use the old prototype like this:
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);
}
}
}());
Upvotes: 1