Extending String.prototype with namespacing?

Hey!

In order to make sure I’m not conflicting with any other library, I want to extend native JS objects with namespacing. For example:

String.prototype.myobj.isEmail();
// and usage will be:
'Some string'.myobj.isEmail()

Normally, using the code below will enable me to extend the standard String obj and add the isEmail method.

Object.assign(String.prototype, {
  isEmail() {
        return /\S+@\S+\.\S+/.test(this);
  }
});

By adding an object first, accessing the string the method was called on with “this” return the added object, and not the actual string, as you can see below:

String.prototype.myobj = {};
Object.assign(String.prototype.myobj, {
  isEmail() {
        // "this" in this context is myobj object literal and not the actual string if called with 'Some string'.myobj.isEmail();
        return /\S+@\S+\.\S+/.test(this);
  }
});

Any ideas?
Thanks!

There’s no way you can do this in Javascript. However, if you are willing to make some compromises, a self-wrapper would do the trick.

String.prototype.myobj = function () {
    const obj = { value: this };
    obj.print = function () {
        return /\S+@\S+\.\S+/.test(this);
    }
    return obj;
}

And you can do

"hello@gmail.com".myobj().isEmail();

However, any modification to native classes is discouraged, and you should not put this code into the production environment.