I've seen two different techniques of implementing non-native features in javascript, First is:
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
}
and Second is:
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
I know that the second one is used to attach any method to the prototype chain of a particular standard built-in objects, but first technique is new to me. Can anybody explain what is the difference between them, why one is used and why one not and what are their significances.
Object.defineProperty
to attempt to understand how it works? – Overpowerenumerable
,configurable
, andwritable
all default tofalse
and thus are not necessary. In any case, the advantage of this is that, uhh, properties so defined are not enumerable, configurable, or writable, all of which you probably want. – Calcdeveloper.mozilla.org
slightly confusing. If we can add a property to prototype of particular standard built-in objects then what doesdefineProperty
actually do, that was confusing part. – Mourant