Background:
According to the MDN bind docs:
A bound function can be further bound by calling boundFn.bind(thisArg, /* more args */), which creates another bound function boundFn2. The newly bound thisArg value is ignored..
This code from the docs is showing how "new this value" (thisArg of boundLog2) is being ignored:
"use strict"; // prevent `this` from being boxed into the wrapper object
function log(...args) {
console.log(this, ...args);
}
const boundLog = log.bind("this value", 1, 2);
const boundLog2 = boundLog.bind("new this value", 3, 4);
boundLog2(5, 6); // "this value", 1, 2, 3, 4, 5, 6
A question:
When importing objects from libraries, something like this:
import obj from library
Is there any way to check ahead if obj
is already bounded?
I want to know if obj
is the result of some previous bind
call, is this possible?
CodePudding user response:
Apparently, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#bound_function you can infer it from the function's .name
. When a function is being bounded, the prefix "bound " is added to the original name and being set as the bounded function's name.
function isBoundedFunction(func) {
return typeof func === 'function' &&
func.name.slice(0, 6) === 'bound ';
}
const namedFunc = () => {}
const boundedFunc = namedFunc.bind("some value");
const boundedAnonimousFunc = (() => {}).bind("some value");
console.log(namedFunc.name, isBoundedFunction(namedFunc));
console.log(boundedFunc.name, isBoundedFunction(boundedFunc));
console.log(boundedAnonimousFunc.name, isBoundedFunction(boundedAnonimousFunc));
Though, I can agree with the commenter who said that it's not something you are usually supposed to do.