Extend a String class in ES6

前端 未结 2 1768
一生所求
一生所求 2020-12-31 11:44

I can write the following in ES5:

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

How do I do the same thi

2条回答
  •  粉色の甜心
    2020-12-31 12:18

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

提交回复
热议问题