class A {
execute() {
}
callback1() {}
callback2() {}
}
window.a = new A();
a.execute = function () {
let bound1 = this.callback1.bind(this);
let bound2 = this.callback2.bind(this);
bound1();
bound2();
}
a.execute();
a.execute = function () {
let bound1 = () => this.callback1();
let bound2 = () => this.callback2();
bound1();
bound2();
}
a.execute();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
bind | |
arrow |
Test name | Executions per second |
---|---|
bind | 60242852.0 Ops/sec |
arrow | 61758584.0 Ops/sec |
Let's break down the provided benchmark.
What is being tested?
The benchmark compares two approaches to bind methods in JavaScript:
bind
method is used to create a new function that has its this
keyword bound to a specified value.=>
syntax is used to define arrow functions, which also have their this
keyword bound to the context in which they are defined.Options being compared
The benchmark compares the performance of two approaches:
bind
method (ES5) to create a new function that binds its this
keyword to the specified value.this
keyword bound to the context in which they are defined.Pros and Cons
Pros:
Cons:
this
incorrectly)Pros:
Cons:
Library and syntax considerations
The benchmark uses the callback1
and callback2
methods, which are likely defined within the provided class definition. The purpose of these methods is to demonstrate how the binding approaches affect their execution.
In this case, there are no notable library or syntax considerations, as both examples rely on standard JavaScript features.
Special JS feature or syntax
There is no special JavaScript feature or syntax being used in this benchmark. Both examples only use the bind
method and arrow functions, which are widely supported features in modern JavaScript.
Other alternatives
If you're interested in exploring alternative approaches to binding methods, here are a few options:
bind
method or arrow functions, you can create a wrapper function that takes the context as an argument and calls the original method with the correct this
value.this
value is used within the closure.In general, when choosing between these approaches, consider factors like performance, code readability, and compatibility across different browsers and versions.