我试图调查jQuery代码,所以我使用了这个:
document.write($.constructor);
斯菲德尔
我得到了这个结果:
function Function() { [native code] }
[native code]
是什么意思?为什么我看不到真实的代码?
经Google-Chrome
测试
当您使用解释型语言(而不是编译语言)定义函数时。您可以访问定义函数的文件/字符串/文本。
例如,在 JavaScript 中,您可以读取已定义的函数的定义正文文本:
function custom( param ){
console.log( param );
}
console.log( custom.toString() ); // <- Will display the full code (in text) of the function.
如果您尝试对 JavaScript 中构造*中包含的函数执行相同的操作,则它不是作为文本实现,而是作为二进制实现。
console.log( setInterval.toString() );
// Will display: function setInterval() { [native code] }
没有理由显示实现该功能的二进制代码,因为它不可读,甚至可能不可用。
jQuery扩展了默认的JavaScript行为。例如.js这是它受到如此高度赞赏和赞扬的原因之一,而不是原型。原型正在改变JavaScript的自然行为,当使用Prototype和其他一些依赖于正常功能的代码时
,可能会产生不一致。博士:
jQuery扩展了JavaScript,有使用本机代码实现的功能(性能方面是一件好事)。
<小时 />*包含在构造中:对这部分进行一些详细说明。 JavaScript本身可以用任何语言(C++,Java等)编写/实现。在Chrome中,JavaScript引擎(V8)是用C++编写的。Firefox的JavaScript引擎(SpiderMonkey)也是用C++编写的。
由语言规范 (ECMAScript) 定义并应包含在实际实现中的函数,用另一种语言编写(例如,在这两种情况下C++),并在 JavaScript 中作为内置/本机函数提供。
这些函数实际上是C++代码编译的(二进制),因此不能在JavaScript本身中显示,例如使用[].map.toString()
语法。
$
,jQuery
只是一个函数。如果不调用它,它只是一个普通的函数。函数的构造函数是Function
的,因此$.constructor
显示[native code]
。
bind 对函数执行此操作:
var f = function() { /* source code */ }; console.log(f.toString());
function () { /* source code */ }
var a = {}; f = f.bind(a); console.log(f.toString());
function () { [native code] }
f = new Function('/* source code */'); console.log(f.toString());
function anonymous() { /* source code */ }
f = f.bind(a); console.log(f.toString());
function () { [native code] }
要么 bind 返回对某种包装器代码的引用,要么 toString 将绑定副本视为本机副本,因为它不是由用户直接创建的
但是,只需直接记录函数,不使用toString(),就会打印(在Chrome中)原始未绑定函数的源代码:
f = f.bind(a); console.log(f)
ƒ () { /* source code */ }
在FF中这不起作用 - FF打印函数对象,没有源代码