- 一个将字符串前缀映射到函数的字典(
functions
) - 一个函数(
get()
),它返回映射到字符串的函数 - 一个函数(
check()
),通过调用get()
并使用!!
将其转换为布尔值来检查是否存在映射到字符串的函数。
functions
中的键调用 get()
时,我希望 check()
返回 true
;但是,它返回了 false
。我在 get()
中执行字典查找并打印两个函数中结果的类型。这里有奇怪的部分。类型仅在 get()
中为 function
;在 check()
中为 undefined
。显然,当我返回它时,该函数被清除或某些东西。如何使 check()
准确?
这是我的简化代码:
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" );
} );
运行此代码将产生以下结果:
"function"
"undefined"
在控制台中。