【问题标题】:Chrome javascript bind function inconsistencyChrome javascript绑定功能不一致
【发布时间】:2011-09-29 00:19:43
【问题描述】:

如果我浏览到 about:blank,请打开脚本控制台并输入以下内容:

var x = function() {
    console.info(this.toString() + ' -- ' + arguments.length.toString());
};
x.bind;

响应显示 x.bind 是用本机代码实现的:

function bind() { [native code] }

但是,当我在 Web 应用程序的页面上调出脚本控制台并执行相同的语句时,看起来 x.bind 并没有原生实现:

function (a){var b=this;return function(){b.apply(a,arguments)}}

什么会导致这个实现像这样切换?我在我的 javascript 中设置的东西可能会导致这种情况吗?我在页面上使用 jQuery - 这会产生影响吗?

【问题讨论】:

    标签: javascript google-chrome ecmascript-5 google-chrome-devtools


    【解决方案1】:

    不是 jQuery,而是其他一些库/脚本将 bind 添加到 Function.prototype,其中一些在不检查它是否已经存在的情况下执行此操作,很高兴地覆盖了本机实现。我假设您必须在页面上使用其他脚本(除了 jQuery),而其他脚本(无论是 jQuery 插件还是其他)在没有检查的情况下被覆盖。

    我刚刚在 Chrome 中进行了测试,无论我是否加载了 jQuery,在实际页面中查看函数的 bind 属性都会显示本机代码标记。 (相比之下,如果我加载最新的 Prototype,它会用自己的方式覆盖 Chrome 的原生版本。)

    Example with page with no libraries,在 Chrome 上输出:

    原型未加载
    未加载 jQuery
    function bind() { [native code] }

    Example with page with latest jQuery,在 Chrome 上输出:

    原型未加载
    找到的 jQuery:1.6.2
    function bind() { [native code] }

    Example with page with latest Prototype,Chrome 上的输出:

    找到的原型:1.7
    未加载 jQuery
    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); } }

    从您的示例中,您没有加载最新的原型,但 something 正在覆盖 Function.prototype.bind

    【讨论】:

    • 谢谢!你说得对——我在我的页面上发现了一个脚本,它正在替换 bind。
    • @Flying:不用担心,很高兴有帮助。 :-)
    猜你喜欢
    • 2022-11-30
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2022-01-03
    相关资源
    最近更新 更多