Вопрос

/*

Is it possible to turn the first block into the second block? I've done something similar with requestAnimationFrame, but because of the dot it does not seem to work here.

*/

////////////////////////////////////////////////////////////////////////////////////////

window.performance = window.performance || {};

window.performance.now = (function()
{
    return window.performance.now       ||
           window.performance.webkitNow ||
           window.performance.msNow     ||
           window.performance.mozNow    ||
           window.performance.oNow      || function() { return new Date().getTime(); };
})();

var PeRfOrMaNcE = window.performance;

console.log(PeRfOrMaNcE.now());

////////////////////////////////////////////////////////////////////////////////////////

var PeRfOrMaNcE = (function()
{
    return window.performance.now       ||
           window.performance.webkitNow ||
           window.performance.msNow     ||
           window.performance.mozNow    ||
           window.performance.oNow      || function() { return new Date().getTime(); };
})();

console.log(PeRfOrMaNcE());
Это было полезно?

Решение

At least in Chrome, the now() function requires that this === window.performance.

You therefore have to use .call or .bind to invoke it correctly.

This appears to work, although it'll still require that window.performance exists, even if it's just initialised to an empty object per your first code attempt:

var PeRfOrMaNcE = (function()
{
    return window.performance.now       ||
           window.performance.webkitNow ||
           window.performance.msNow     ||
           window.performance.mozNow    ||
           window.performance.oNow      || function() { return new Date().getTime(); };
})().bind(window.performance);

or alternately, avoiding the .bind call when window.performance doesn't exist:

var PeRfOrMaNcE = (function()
{
     var wp = window.performance;
     var now = wp && (wp.now || wp.webkitNow || wp.msNow || wp.mozNow || wp.oNow);

     return now && now.bind(wp) || function() {
         return new Date().getTime();
     }
})();

Другие советы

Fixed.

Concise, but slightly more obfuscated.

var PeRfOrMaNcE = function()
{
    var wp = window.performance;
    var v = ['now', 'webkitNow','msNow','mozNow', 'oNow'];
    for (var i in v) {
        if (wp[v[i]]) return wp[v[i]]()
    }
    return (new Date()).getTime();
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top