Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exporting Object.defineProperty

I have this piece of code:

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });
}

How can I export startsWith from A.js to B.js usingA.startsWith()?

I tried to use exports Object.defineProperty(String.prototype, 'startsWith', { but I’m getting errors

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In file B.js, I’m using import * as A from './A.js', but I’m unable to use A.startsWith().

How can I solve it?

Thank you.

>Solution :

Because the code only performs side-effects, it doesn’t really make sense for it to be imported to a variable in a different module. Importing it for its side-effects will be enough to use String.prototype.startsWith.

// A.js
if (!String.prototype.startsWith) {
  // etc
// B.js
import './A.js';
console.log('abc'.startsWith('a')); // true

If you must export something, and you don’t want side-effects just from importing, you could export a function that, when called, assigns to the prototype.

// A.js
export const polyfillStartsWith = () => {
  if (!String.prototype.startsWith) {
    // etc
// B.js
import { polyfillStartsWith } from './A.js';
polyfillStartsWith();
console.log('abc'.startsWith('a')); // true
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading