I would like to determine which is the best practice between equivalent solutions. The use case is an instance of a class that listen to an event. Dr. Axel Rauschmayer prefers the lambda for readability. I agree with him. But in term of performance and memory consumption, which is the best?
With a lambda function
class Abc {
constructor() {
let el = document.getElementById("my-btn")
if (el)
el.addEventListener("click", evt => this.onClick(evt))
}
onClick(evt) {
console.log("Clicked!", evt.target)
}
}
Can someone to confirm or infirm if the local variables (here el
) can't be cleared by the garbage collector? Or, are modern browsers capable to detect they are unused in the closure?
With Function.prototype.bind
:
class Abc {
constructor() {
let el = document.getElementById("my-btn")
if (el)
el.addEventListener("click", this.onClick.bind(this))
}
onClick(evt) {
console.log("Clicked!", evt.target)
}
}
There is no memory issue, but all benchmarks suggest that bind
is far slower than a closure (an example here).
EDIT: I don't agree with the comments that ignore the performance issue of bind
. I suggest to read this answer with the code of the implementation in Chrome. It cannot be efficient. And I insist: all the benchmarks I saw, show similar results on all browsers.
Is there a way to have a low memory usage and a good performance at the same time?