如果我浏览到 about:blank,打开脚本控制台并输入以下内容:
var x = function() {
console.info(this.toString() + ' -- ' + arguments.length.toString());
};
x.bind;
响应显示 x.bind 是在 native 代码中实现的:
function bind() { [native code] }
但是,当我在我的 Web 应用程序的页面上拉出脚本控制台并执行相同的语句时,x.bind 似乎并未在本地实现:
function (a){var b=this;return function(){b.apply(a,arguments)}}
什么会导致这个实现像这样切换?我在我的 javascript 中设置的东西可能会导致这种情况吗?我在页面上使用 jQuery - 这会产生影响吗?
最佳答案
不是 jQuery,而是其他一些库/脚本添加 bind
至 Function.prototype
,他们中的一些人在没有检查它是否已经存在的情况下就这样做了,很高兴地覆盖了 native 实现。我假设您必须在页面上使用一些其他脚本(除了 jQuery),并且其他脚本(无论是 jQuery 插件还是其他)正在覆盖而不检查。
我刚刚在 Chrome 中进行了测试,无论我是否加载了 jQuery,都是从实际页面中查看函数的 bind
属性显示 native 代码标记。 (相比之下,如果我加载最新的 Prototype,它会用自己的版本覆盖 Chrome 的 native 版本。)
Example with page with no libraries , 在 Chrome 上输出:
Prototype not loaded
jQuery not loaded
function bind() { [native code] }
Example with page with latest jQuery , 在 Chrome 上输出:
Prototype not loaded
jQuery found: 1.6.2
function bind() { [native code] }
Example with page with latest Prototype , 在 Chrome 上输出:
Prototype found: 1.7
jQuery not loaded
function bind(context) { if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; var __method = this, args = slice.call(arguments, 1); return function() { var a = merge(args, arguments); return __method.apply(context, a); } }
在您的示例中,您没有加载最新的原型(prototype),但某些东西正在覆盖 Function.prototype.bind
.
关于javascript - Chrome javascript 绑定(bind)函数不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6586505/