0

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?

nonopolarity
  • 130,775
  • 117
  • 415
  • 675
  • 1
    This should help explain the reason, at least: [Meaning of “this” in node.js modules and functions](https://stackoverflow.com/questions/22770299/meaning-of-this-in-node-js-modules-and-functions). Also: [In what scope are module variables stored in node.js?](https://stackoverflow.com/questions/15406062/in-what-scope-are-module-variables-stored-in-node-js) – Jonathan Lonowski Dec 14 '19 at 03:28
  • so if `this` is still a reference to an object and `this.now` is assigned something, then `this.now()` should still work? – nonopolarity Dec 14 '19 at 03:42
  • The issue is that the value of `this` isn't referring to the same object in each case. Node.js sets its initial value for the file to `module.exports` while `getNow()` will use the language default of the `global` object. Using `export.now` (or `global.now`) directly in place of `this.now` can resolve the difference. Another option is to [make it into a UMD](https://github.com/umdjs/umd/blob/master/templates/commonjsStrict.js). – Jonathan Lonowski Dec 14 '19 at 04:07

0 Answers0