Home > Back-end >  Exporting Object.defineProperty
Exporting Object.defineProperty

Time:12-13

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

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.

CodePudding user response:

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
  • Related