Search code examples
javascriptbrowserunderscore.jsv8native-code

How does Undersore's _.now work?


It doesn't look like it is written in JavaScript.

if you type _now in the console, you only get

function now() { [native code] }

You usually only get that when you try to look at some built-in method where the inner-workings are invisible to the browser.

setTimeout
=>function setTimeout() { [native code] }

Has _.now done something with "native code" of the JavaScript engine?


Solution

  • By default _.now is just Date.now, except in environments that do not support it. Where Date.now isn't supported _.now will use this implementation instead (same goes for lodash)

    _.now = function() {
       return (new Date()).getTime()
    };
    

    As your browser supports Date.now, _.now is just a proxy to the native implementation


    Note: you can also make any of your functions appear as native in console by calling using Function.prototype.bind

    function foo() {console.log('bar');}
    var bar = foo.bind(null);
    
    console.log(bar);
    // => function () { [native code] }