Skip to content Skip to sidebar Skip to footer

Javascript Binding - Arrow Functions And Bind

I have this bit of code: const data = { x: 'Target' } let bar = () => { console.log(this.x) } let final = bar.bind(data); final(); This code returns undefined. Here is

Solution 1:

But does it also prevent bind() from working?

Partially, because bind returns a new function that calls the original function with a specific this — but arrow functions don't use the this they're called with, they completely ignore it. Instead, they close over the this where they're defined.

bind on an arrow function can't change the arrow's concept of this. All it can do is its secondary feature, pre-supplying arguments:

"use strict";
functionrun() {
  constf = (a, b, c) => {
    console.log("this", this);
    console.log("a", a);
    console.log("b", b);
    console.log("c", c);
  };

  const fbound = f.bind({}, 1, 2, 3);
  f();
  fbound();
}
run();
.as-console-wrapper {
  max-height: 100%!important;£
}

Solution 2:

Arrow function takes precedence over bind. Whenever there are two or more different ways of setting this context, they are resolved in the following order: -arrow functions -new keyword -bind -call or apply

Post a Comment for "Javascript Binding - Arrow Functions And Bind"