在ES6中扩展String类 [英] Extend a String class in ES6

查看:99
本文介绍了在ES6中扩展String类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在ES5中编写以下内容:

I can write the following in ES5:

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

如何使用新功能在ES6中做同样的事情?

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

我知道这也是有效的ES6.我想知道在ES6中是否还有其他实现此类功能的方法?
上面的功能只是一个例子.

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.

推荐答案

在ES6中,您也可以使用Object.assign()来做到这一点:

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.

或者您可以使用defineProperty(我认为这会更好):

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

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

此处中查看文档

请参阅我的评论,以了解何时使用definePropertyObject.assign().

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

这篇关于在ES6中扩展String类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆