I have:
functions) mapping string prefixes to functionsget()) that returns the function mapped to a stringcheck()) that checks if there's a function mapped to a string by calling get() and casting it to a boolean with !!.When I call get() with a key in functions, I expect that check() returns true; however, it returns false. I perform the dictionary lookup in get() and print the type of the result in both functions. Here's the weird part. The type is function only in get(); in check(), it's undefined. Apparently, the function gets erased or something when I return it. How can I make check() accurate?
Here's my simplified code:
var someObject = {
functions: {
"a": function () { return 0; },
"b": function () { return 1; }
},
get: ( function ( someVariable ) {
Object.keys( this.functions ).forEach( ( function ( functionKey ) {
if ( someVariable.startsWith( functionKey ) ) {
console.log( typeof this.functions[ functionKey ] );
return this.functions[ functionKey];
}
} ).bind( this ) );
} ),
check: function ( stringToCheck ) {
var returnedFunction = this.get( stringToCheck );
console.log( typeof returnedFunction );
return !!returnedFunction;
}
}
$( document ).ready( function () {
someObject.check( "a" );
} );
Running this code produces this:
"function"
"undefined"
in the console.
It's because forEach does not break early/short circuit on the return statement (it continues with the next iteration, and then the get function returns undefined). You could re-write the loop to allow breaking (say, with a simple for-loop), or you could return the value after looping, such as:
var someObject = {
functions: {
"a": function () { return 0; },
"b": function () { return 1; }
},
get: ( function ( someVariable ) {
var func;
Object.keys( this.functions ).forEach( ( function ( functionKey ) {
if ( someVariable.startsWith( functionKey ) ) {
console.log( typeof this.functions[ functionKey ] );
func = this.functions[ functionKey];
}
} ).bind( this ) );
return func;
} ),
check: function ( stringToCheck ) {
var returnedFunction = this.get( stringToCheck );
console.log( typeof returnedFunction );
return !!returnedFunction;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With