Import JavaScript prototype extension

666 views Asked by At

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?

1

There are 1 answers

1
Pankaj Karki On BEST ANSWER

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.

export default { round: Number.prototype.round, foo }

Then either you use it directly as

SomeLib.round.call(someNum, 2)

Or you can set the prototype of Number in this file.

Although not sure, why the already defined Number prototype didn't work.