admin管理员组

文章数量:1178553

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.

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.

Share Improve this question edited Jul 29, 2019 at 5:06 brasofilo 26.1k15 gold badges93 silver badges185 bronze badges asked May 15, 2015 at 11:05 ritz078ritz078 2,3373 gold badges23 silver badges24 bronze badges 6
  • 1 Is the example code your actual use case or are you talking about extending String.prototype in general? – Qantas 94 Heavy Commented May 15, 2015 at 11:57
  • 1 All ES5 code is also valid ES6 code. So you can just use the same code. – Felix Kling Commented May 15, 2015 at 13:47
  • @Qantas94Heavy I was talking for a general case. – ritz078 Commented May 15, 2015 at 14:50
  • 1 Might be worth noting that you can't update to arrow functions as the value for this is provided by their lexical scope. – KyleMit Commented Jun 30, 2019 at 21:37
  • It's worth noting that extending native objects like this, while not strictly prohibited, is pretty much never a good idea. See stackoverflow.com/questions/14034180/… for more. (tl;dr: Changes the behavior of the object in subtle and not-so-subtle ways that may break other code.) – broofa Commented Dec 17, 2019 at 16:59
 |  Show 1 more comment

2 Answers 2

Reset to default 31

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).

本文标签: javascriptExtend a String class in ES6Stack Overflow