这是我的代码:
function convertStringToFunction(string) {
var fn = String.prototype[string];
// need to replace 'String' with something
return (typeof fn) === 'function';
}
convertStringToFunction('reduce'); // => false but need to return true
convertStringToFunction('toUpperCase') // => true
目标是使用函数名字符串搜索和调用内置函数。
但是,如果字符串可以使用任何函数名称,如reduce
和toUpperCase
。
如何确保fn
始终是一个功能?换句话说,前一个函数应该始终为真。
答案 0 :(得分:2)
我认为这就是你想要的:
// this is currently the *only* certain way to get a
// reference to the global object
var global = new Function('return this;')();
// this is dicey, see note below
var isNative = function(fn) {
return fn.toString().match(/native code/i);
};
// this will return a true if the passed in name is a built-in
// function of any of the global constructors or namespace objects
// like Math and JSON or the global object itself.
var isBuiltInFunction = function(name) {
var tests = [
global,
String,
Function,
RegExp,
Boolean,
Number,
Object,
Array,
Math,
JSON
];
// test for native Promises
if (typeof Promise === 'function' && isNative(Promise)) {
tests.push(Promise);
}
// test for document
if (typeof document !== undefined) {
tests.push(document);
}
// test for Symbol
if (typeof Symbol === 'function' && isNative(Symbol)) {
tests.push(Symbol);
}
return tests.some(function(obj) {
return typeof obj[name] === 'function' && isNative(obj[name]);
});
};
请注意,Function.prototype.toString
与实现有关,这可能不适用于所有平台。您可以省略它,但它会将这些用户定义的版本计为“内置”。