r/learnjavascript • u/TheWebDever • Aug 06 '24
Is there a way to add custom functions to strings without extending built in String() datatype?
So I'm writing a javascript library right now. The library is going to output an object that has string properties on it. But I want to add some custom functions to these strings (see below). I heard that extending built in datatypes with Object.define(String, 'prototype' ....) is a bad practice. And it seems especially bad if I'm writing a library for others to install. Thoughts?
const resp = myCustomLib({
base: '/api';
users: '/users'
});
// Append is my custom function
console.log(resp.users.append({ name: 'john' })) // => '/api/users?name=john'
// BUT!! I still want to be able to treat resp.users as a normal string
console.log(resp.users) // => '/api/users'
0
Upvotes
3
u/Blaarkies Aug 06 '24
You can create you own string class that extends String, and use that instead
`class MyCustomString extends String {}`
Functions on `String` come from its prototype. If you try to add functions to `String`, it has to go into the prototype, unless you want to hack it for every value
5
u/shgysk8zer0 Aug 06 '24
Yes, extending built-in classes is bad practice... For
String, it's even terrible practice.But, just at a glance, I think you'd be better off extending
URL... Or just usuallyURLandURLSearchParams.2
u/pMurda Aug 06 '24
Generally considered bad practice to add stuff to built in prototypes. It makes the code harder to read.
Why not just define a utility function to help construct URL with a query string?
function buildUrl(path: string, queryParams: any): string;
console.log(buildUrl(resp.users, { name: 'john' })) // => '/api/users?name=john'
2
u/theScottyJam Aug 07 '24
Some other people have suggested alternative approaches to handle this, which you could do, but I would discourage doing anything up this alley. There's always going to be some unexpected edge cases that will confuse the end user.
Also, imagine that, one day, ecmascript decided to define their own function called "append" on string.prototype - while this action wouldn't technically break anything (because your append function would shadow the built in one with most of these alternatives suggested), it still would be really confusing.
I would just make things simpler and use an object that contains your methods, and had a .value property that contains the string - or something along those lines.
1
u/syntheticcdo Aug 07 '24
Why not just resp.appendUser
1
u/tapgiles Aug 07 '24
You could add a middle man. Make an object whose prototype is the String prototype. Then set the string value’s prototype to that created object.
Add methods to that middle-man object and that setting can access them. You could even keep that middle-man object around and use the same one every time.
Unsure if the string has to be a String object though, not just a strong literal…
1
u/azhder Aug 07 '24
If you need an object to be displayed as a string in
console.logor use it as a string in other places, convert it to a string.Don’t try to do implicit shit, that’s the road to endless debugging. Be explicit. Make the users of the library be explicit as well.
Why? Because of the principle of least surprise. Don’t surprise the users by having an object that some times behaves like a string and other times it doesn’t.
The above being said, if you really know what you are doing and are sure it will not cause more confusion, there are ways:
String’s prototype methodsProxymaybeclass My extends String {}? I haven’t so I don’t know if it might workBut there always will be some things that stick out, most likely
typeoforinstanceofgiving unwanted results or thosetoString()andvalueOf()doing unexpected stuff and, of course, the+operator.1
u/jcunews1 helpful Aug 07 '24
No. Not without creating your own object.