4👍
debounce(function() {...})
is an expression. onKeyUp
is assigned to the result of its evaluation. The result of debounce
call is debounced function, so is onKeyUp
.
I would expect when onKeyUp is triggered, it would run debounce
This isn’t how JavaScript works. Given var foo = 1 + 1
, 1 + 1
is eagerly evaluated to 2, not at the time when foo
variable is accessed. The only possibility for the code to be lazily evaluated is to wrap it inside a function. This is what happens in case of debounce
. The code inside function() {...}
is called after a delay when debounced function is called. debounce
itself is called when it’s called.
Also, why does it need to be a non-arrow function in the second example
Because this is the only way the function can get component instance as this
. Since arrows don’t have their own context, this
would refer to outer context with an arrow, which is module context in which the component is defined:
onKeyUp: debounce(() => {...})
and
onKeyUp: () => {...}