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.
2 Answers
Reset to default 31In 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
版权声明:本文标题:javascript - Extend a String class in ES6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737995970a2046402.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
String.prototype
in general? – Qantas 94 Heavy Commented May 15, 2015 at 11:57this
is provided by their lexical scope. – KyleMit ♦ Commented Jun 30, 2019 at 21:37