javascript内置全局对象的通用术语
这是我的密码:javascript内置全局对象的通用术语,javascript,object,built-in,Javascript,Object,Built In,这是我的密码: 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 c
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
目标是搜索并调用具有函数名字符串的内置函数。
但是,if字符串可以采用任何函数名,如reduce
和toUpperCase
。
如何确保fn
始终是一个函数?换句话说,前面的函数应该总是正确的。我想这就是您想要的:
// 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
依赖于实现,这可能不适用于所有平台。您可以忽略它,但它会将这些函数的用户定义版本计算为“内置函数”。代码没有问题,字符串没有reduce
函数……我希望convertStringToFunction()将字符串转换为任何内置函数,就像它存在一样。所以我想知道是否存在类似allBuiltinObjec.prototype的东西。那么为什么要检查函数名是否是String.prototype
?全局名称是window[String]
。但是没有全局reduce
函数,它是Array.prototype
的一个属性。也没有全局toUpperCase
函数,它只是String.prototype
的一个属性。没有一个地方可以让您查找所有内置原型的属性。我认为您的代码中存在一些bug。但我现在明白你的意思了。谢谢