javascript 在 ES6 中扩展 String 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30257915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extend a String class in ES6
提问by ritz078
I can write the following in ES5:
我可以在 ES5 中编写以下内容:
String.prototype.something=function(){
return this.split(' ').join('');
};
How do I do the same thing in ES6 using the new features?
如何使用新功能在 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。我想知道在 ES6 中是否还有其他更短的实现此类功能的方法?
上面的函数只是一个例子。
回答by AWolf
In ES6 you can also do it with Object.assign()
like this:
在 ES6 中,你也可以这样做Object.assign()
:
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):
或者你可以使用defineProperty
(我认为这里会更好):
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()
.
请参阅我的评论以了解何时使用defineProperty
vs Object.assign()
。
回答by ritz078
Your proposal works fine in ES6, is there something wrong with it?
你的提议在 ES6 中运行良好,有什么问题吗?
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:
如果你想真正扩展String
,而不是仅仅为String
它自己添加一个方法,并获得那种温暖的 ES6 感觉,你可以尝试:
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).
错误消息(来自 babel-node)。