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!