问题
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