简体   繁体   中英

Extend a String class in ES6

I can write the following in ES5:

String.prototype.something=function(){
  return this.split(' ').join('');
};

How do I do the same thing in ES6 using the new features?

I know that this is also a valid ES6. I want to know whether there's any other way of implementing such functions in ES6 which is shorter?
The above function is just an example.

In ES6 you can also do it with Object.assign() like this:

Object.assign(String.prototype, {
    something() {
        return this.split(' ').join();
    }
});

You can find more info to the method here .

Or you could use defineProperty (I think that would be better here):

Object.defineProperty(String.prototype, 'something', {
    value() {
        return this.split(' ').join();
    }
});

See the docs here .

See my comment to see when to use defineProperty vs Object.assign() .

Your proposal works fine in ES6, is there something wrong with it?

If you want to actually extend String , instead of just adding a method to String itself, and get that warm ES6 feeling, you could try:

class MyString extends String {
    something() { return this.split(' ').join(''); }
}

However, you are going to quickly run into limitations on extending built-in classes. Chances are you will see the dreaded

TypeError: String.prototype.toString is not generic

error message (this is from babel-node).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM