Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
1252748 Avatar asked Feb 04 '26 20:02

1252748


2 Answers

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] }
like image 116
megawac Avatar answered Feb 07 '26 10:02

megawac


Take a look at the underscore source code:

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

This means that it will use Date.now() if it exists, which is an internal function. Otherwise it will use new Date().getTime(), which is supported by all JavaScript engines.

like image 26
Jivings Avatar answered Feb 07 '26 11:02

Jivings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!