I am attempting to write some code that works in most browsers and inside of the Node environment:
if (!this.window) this.now = require("performance-now")
function getNow() {
return this.window ? performance.now() : this.now();
}
console.log("Now is ", getNow());
The code works well in Google Chrome, Firefox, Safari, and when pasted to a Node console. But if I run it using
$ node my_code.js
then it'd say
return this.window ? performance.now() : this.now();
^
TypeError: this.now is not a function
Why is that and what might be a better version? (it'd be best not to introduce an extra variable now
if it is in the browser environment).
P.S. One way I found that can work in most browsers, inside of Node console, and as a standalone JS file using Node.js is:
const getNow = this.window ? performance.now.bind(performance) : require("performance-now");
console.log("Now is ", getNow());
But what is the reason method 1 using this.now()
does not work?