Extend the String class in ES6
I can write the following in ES5:
String.prototype.something=function(){
return this.split(' ').join('');
};
How can I do the same in ES6 using the new features?
I know this is also valid ES6. I want to know if there is another way to implement such functionality in ES6 that is shorter?
The above function is just an example.
source to share
In ES6, you can also do it with the Object.assign()
following:
Object.assign(String.prototype, {
something() {
return this.split(' ').join();
}
});
More about the method here .
Or you could use defineProperty
(I think it would be better here):
Object.defineProperty(String.prototype, 'something', {
value() {
return this.split(' ').join();
}
});
See the docs here .
See my comment to learn when to use defineProperty
vs Object.assign()
.
source to share
Your suggestion works great in ES6, is there something wrong with it?
If you want to actually extend String
instead of just adding a method to String
yourself and get that warm ES6 feel, you can try:
class MyString extends String {
something() { return this.split(' ').join(''); }
}
However, you will soon run into restrictions on extending built-in classes. Most likely you will see a terrible
TypeError: String.prototype.toString is not generic
error message (this is from babel-node).