I saw two different methods for implementing non-local functions in javascript, First:
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:
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
I know that the second is used to attach any method to the prototype chain of certain standard built-in objects, but the first technique is new to me. Can anyone explain what the difference is between the two, why one is used, and why not, and what their meanings are.
source
share