Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript内置全局对象的通用术语_Javascript_Object_Built In - Fatal编程技术网

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。但我现在明白你的意思了。谢谢