【问题标题】:Why the following js code is not working?为什么下面的js代码不起作用?
【发布时间】:2013-11-07 18:11:53
【问题描述】:

代码

var x = {};

x.request = window.requestAnimationFrame;

function step(timestamp) {

    console.log('sth');
}

x.request(step);

返回:

NS_ERROR_XPC_BAD_OP_ON_WN_PROTO:对 WrappedNative 的非法操作 原型对象

它应该使 x.request 与 window.requestAnimationFrame 一样工作。 我需要它,因为我想做类似的东西:

x.request = window.requestAnimationFrame
                ||
            window.webkitRequestAnimationFrame
                ||
            window.mozRequestAnimationFrame;

【问题讨论】:

  • An article 来自 Paul Irish,带有 polyfill
  • 是的,但是将它分配给窗口对象并不是我一直在寻找的。​​span>

标签: javascript window requestanimationframe


【解决方案1】:

试试

x.request.call(window, step);

这将确保this 是window。

【讨论】:

    【解决方案2】:

    这是上下文的问题。上下文是函数内部this的值。

    例如:

    var a = {
        name: 'object a',
        fn: function() {
            return name;
        }
    },
        b = {
        name: 'object b'
    };
    
    b.fn = a.fn;
    console.log(b.fn());
    

    你会得到什么结果?你可能认为你会得到'object a',因为这就是函数的定义方式。事实上你会得到object b,因为这就是函数的调用方式。您正在为函数调用提供 context,该上下文是对象 b。

    您可以看到与您的代码的明显相似之处!

    x.request = window.requestAnimationFrame;
    x.request(step);
    

    现在,调用的上下文是 x。显然requestAnimationFrame 关心它的上下文,不会与错误的上下文一起工作。

    因此,您需要提供正确的。有两种方法可以做到这一点。您可以在调用函数时使用Function#call 设置上下文,也可以使用Function#bind 提前设置上下文:

    // with call
    x.request.call(window, step); // provide the window object as the context
    
    // with bind
    x.request = window.requestAnimationFrame.bind(window);
    

    (但请注意,并非所有浏览器都支持bind,因此您需要provide a shim for those that don't。)

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 2016-03-21
      • 2018-12-15
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2017-03-17
      相关资源
      最近更新 更多