javascript 内置全局对象的总称

general term for javascript built-in global object

这是我的代码:

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

目标是搜索并调用一个带有函数名字符串的内置函数。 但是,如果字符串可以采用任何函数名称,如 reducetoUpperCase。 如何确保 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 是依赖于实现的,这可能不适用于所有平台。您可以省略它,但随后它将把这些用户定义的版本计为 'built-in'.