Why is this…
String.prototype.repeat = function (times) {
return new Array(times + 1).join(this);
}
console.log('awe'.repeat(3)) // 'aweaweawe'
…considered bad?
It's not considered bad per-se. When working on your personal app or website, you can do anything you want. But here are a few situations where you might want to reconsider:
String.prototype.repeat() (actually, it already exists)? You will have to change your code, because it is not forward compatible and you have no control over the browser version used to view your siteInstead of extending the base object prototype like that, I would recommend writing a wrapper, or, even better, a Mixin(composable objects):
const Repeatable = (superclass) => class extends superclass {
repeat (times) {
return new Array(times + 1).join(this);
}
};
class MyString extends Repeatable(String) {
constructor(str) {
super(str);
}
};
var str = new MyString('Hellow!');
console.log(str.repeat(3));
Peter Scheler
JS enthusiast
Because:
But it is OK to use polyfills (and add-ons) like that:
if (!('entries' in Object)) { Object.defineProperty(Object, 'entries', { value: function(obj) { return Object.keys(obj).map(function(key) {return [key, obj[key]]}) } }) }PS: Sorry,
entriesis not defined on Object.prototype, but you know what I mean.