How does Undersore's _.now work?

安稳与你 提交于 2019-12-02 00:54:25
megawac

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

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.

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

_.now(); => 1392066795351

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