isNative 方法

  • 源码地址: /src/core/util/env.js
  • 描述:用于判断是否是浏览器原生 JS 方法

源码

1
2
3
export function isNative (Ctor: any): boolean {   
  return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}

解析

[native code 是什么?]


  1. toString 可以将整个函数内容转换为字符串输出
1
2
3
4
5
6
function f1 (){  
    const a = 1;
}

console.log(f1.toString()) 
//-> 'function f1 (){ const a = 1; }'
  1. toString 只能输出用户创建的方法细节,浏览器 js 引擎开发实现的方法不会输出细节
1
2
console.log(Array.isArray.toString())  
//-> 'function isArray() { [native code] }'

[native code]


  1. [native code] 意思已经很明确了:是 native 的代码实现的 built-in 函数,而不是 JavaScript 代码。
  2. An implementation-dependent representation of the function is returned.
  3. [native code] 的返回形式并不是语言标准规定的,只是恰好 FireFox、Chrome 都这么干了。

[语言标准]


15.2.4.2 Function.prototype.toString()

An implementation-dependent representation of the function is returned.This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation String is implementation-dependent.

The toString function is not generic; it throws a TypeError exception if its this value is not a Function object. Therefore, it cannot be transferred to other kinds of objects for use as a method.

函数返回值的依赖于实现的表示形式。

[V8 实现细节]


v8natives.js 第 1710 行附近的 FunctionSourceString 函数:

1
return'function () { [native code] }';

这就是 V8 是怎么返回 [native code] 这一串字符串的。


isNative 方法
https://blog.pangcy.cn/2022/10/15/前端编程相关/前端框架与库/Vue/Vue2 源码分析/isNative 方法/
作者
子洋
发布于
2022年10月15日
许可协议