How does Undersore's _.now work?

孤人 提交于 2019-12-02 05:14:58

问题


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?


回答1:


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] }



回答2:


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.




回答3:


It returns an integer timestamp for the current time. Useful for implementing timing/animation functions.

_.now(); => 1392066795351



来源:https://stackoverflow.com/questions/28227187/how-does-undersores-now-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!