Extend a String class in ES6

前端 未结 2 1771
一生所求
一生所求 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:29

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

提交回复
热议问题