Reading a piece of TypeScript (context Angular) came across a perplexing usage of the JavaScript bind function. Can anyone explain this pattern?
Example 1
const f = this.bind('astring');
return f ? f(someArgs) : someDefaultReturn;
The pattern in the first line is used a number of times here.
Per the docs, the usage for bind says it’s called on a function and is passed an object like so:
Example 2
const f = someFunc.bind(someObject);
Where f is a function that calls someFunc and makes its ‘this’ context equal to someObject when f is called, which all makes sense.
But when the code in the pattern in example 1 at the top is run, someFunc (‘this’) turns out to be an object (actually an instance of a class which has ‘bind’ so yes, it may technically be a function) and someObject (‘astring’) is a primitive not an object (yes, I know all primatives are actually wrapped in objects). It’s completely thrown me.
What is this code doing and how?