@nevware21/ts-utils
    Preparing search index...

    Function isNativeFn

    • Checks whether the value is a native function, a function which isn't written in JavaScript (eg. a built-in function like Array or Math.max, a function returned by the native Function.prototype.bind() or a callable Proxy), and when a name is provided, whether it is the native function with that name.

      Its source text, from the intrinsic Function.prototype.toString() (captured when the module is loaded, so one which is replaced later, or a function's own toString(), isn't used), is matched against the NativeFunction syntax which the ECMAScript specification requires for these functions, eg. function Array() { [native code] } (a runtime may add whitespace, eg. new lines), in linear time. The source text of a function written in JavaScript is its code, which can't have this syntax as [native code] isn't valid JavaScript, except where the runtime doesn't return its code: V8 (eg. Chrome and Node) returns a native source text for a function which has more than 65,535 characters between the function keyword and its parameters (eg. function followed by 65,536 spaces and Array() {}), so (as the source text is all it uses) such a function is also identified as a native function there. So it identifies the runtime's functions (eg. to choose a native implementation), it isn't a security check of a value which may have been created to look like a native function.

      It returns a boolean rather than being a type guard, as a false result doesn't mean that the value isn't a function (a function written in JavaScript also returns false), use isFunction to narrow the type.

      Parameters

      • value: any

        The value to check

      • Optionalname: string

        The name of the native function (its initial name, eg. "Array", "max", "get size" for a getter, or "" for an anonymous one such as a bound function), when it isn't provided any native function matches

      Returns boolean

      true when the value is a native function (with the name), otherwise false

      0.20.0

      isNativeFn(Array);                // true
      isNativeFn(Array, "Array"); // true
      isNativeFn(Math.max, "max"); // true
      isNativeFn(Math.max, "min"); // false
      isNativeFn(function Array() {}); // false, written in JavaScript
      isNativeFn(() => {}); // false
      isNativeFn(Array.bind(null)); // true, eg. "function () { [native code] }"
      isNativeFn("function Array() { [native code] }"); // false, not a function

      // Another realm's (eg. an iframe's) Array is also the native Array
      isNativeFn(iframe.contentWindow.Array, "Array"); // true