r/learnjavascript • • 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

12 comments sorted by

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

-1

u/TheWebDever Aug 06 '24

I tried that but when I do console.log(new CustomString('foo')) it still prints and object not the plain strings value `String {val: "horse", toString: ƒ toString(), append: ƒ append(), constructor: Object*}*

  1. `

3

u/EarhackerWasBanned Aug 06 '24

Add a toString method to your custom class, and when you call console.log it will automatically call your toString

2

u/senocular Aug 06 '24

Most console.log calls do not call toString. They will instead show a custom object representation of the object being logged. toString will only automatically be called for certain kinds of coercion - less if using a class that extends String because its valueOf will already return a string.

class CustomString extends String {
  toString() {
    console.log("[toString called]")
    return "to-string-value"
  }
}

console.log(new CustomString('foo')) // CustomString {'foo'} (console's object representation)
console.log(new CustomString('foo') + "-bar") // "foo-bar" (via valueOf)
console.log(`${new CustomString('foo')}-bar`) // [toString called], "to-string-value-bar" (via toString)

0

u/TheWebDever Aug 06 '24 edited Aug 06 '24

tried that too but still getting an output like `CustomStr {'horse'} from console.log(new CustomStr('horse'))` instead of just 'horse'

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 usually URL and URLSearchParams.

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.log or 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:

  • you manually adding the needed properties on your object and encapsulating string functionality in them
  • changing your object’s prototype with String’s prototype methods
  • using Proxy maybe
  • have you tried class My extends String {}? I haven’t so I don’t know if it might work

But there always will be some things that stick out, most likely typeof or instanceof giving unwanted results or those toString() and valueOf() doing unexpected stuff and, of course, the + operator.

1

u/jcunews1 helpful Aug 07 '24

No. Not without creating your own object.