I found (on this site) a cool little prototype extension function for cleaning up numbers, and now want to use this in a library that I can then import as needed. I see how to import defined functions but not prototype extensions.
file: SomeLib.js
"use strict";
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
function foo() {
console.log("doing SomeLib.foo()");
}
export default { round, foo }
file: SomeImporter.js
"use strict";
import somelib from "./SomeLib.js";
somelib.foo(); // outputs 'doing SomeLib.foo()'
var someNum = 1.2345;
console.log(someNum.round(2)); // outputs 'Uncaught ReferenceError: round is not defined'
How can I import the 'Number.prototype.round' function in another file?
Not sure why someNum.round() would throw an error even when the round is already defined in the prototype of Number in file imported. (Number.prototype.round in someLib.js)
Now, Since you have returned round which is not defined anywhere in someLib.js You can actually pass the reference of Number.prototype.round as below.
Then either you use it directly as
Or you can set the prototype of Number in this file.
Although not sure, why the already defined Number prototype didn't work.