Skip to main content

Command Palette

Search for a command to run...

JavaScript Auto-bound behavior of arrow functions

Updated
1 min read

Consider

class c {
    a=1;

  autoBound = () => {console.log(this.a);}
}

const C=new c();

const {autoBound}=C;
console.log(autoBound);
autoBound();

Output

() => {console.log(this.a);}
1

As you can see, even when autoBound has been extracted out from an instance of c, its this is still pointing to the instance C. We call this being auto bound.

Even if we try to manually set this by something like autoBound.call({a:500}) and expecting something different (like logging 500 instead), it still prints 1. In other words, this can't be over-written.

Now consider this when autoBound is in normal function form.

class c {
    a=1;

  autoBound = function() {console.log(this.a);}
}

const C=new c();

const {autoBound}=C;

autoBound.call({a:1000});

Output

1000

This time we can provide a custom this as 1000 and that is the output we get from calling autoBound().

JavaScript Auto-bound behavior of arrow functions