JavaScript で非ネイティブ機能を実装する 2 つの異なる手法を見てきました。最初は次のとおりです。
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;
}
});
}
2番目は次のとおりです。
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
2 番目の方法は、特定の標準組み込みオブジェクトのプロトタイプ チェーンに任意のメソッドを追加するために使用されることは知っていますが、最初の方法は私にとって初めての方法です。それらの違いは何か、なぜ使用され、使用されないのか、そしてそれらの重要性を説明できる人はいますか。