16

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 番目の方法は、特定の標準組み込みオブジェクトのプロトタイプ チェーンに任意のメソッドを追加するために使用されることは知っていますが、最初の方法は私にとって初めての方法です。それらの違いは何か、なぜ使用され、使用されないのか、そしてそれらの重要性を説明できる人はいますか。

4

1 に答える 1

30

2 つのケースでは、新しいプロパティ「startsWith」を に追加していますString.prototype

この場合、1 番目は 2 番目とは異なります。

プロパティをenumerablewritableおよびに構成できますconfigurable

書き込み可能-true任意の値を割り当てることで値を変更できることを意味します。false の場合 - 値を変更できません

Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: false,
        configurable: false,
        writable: false, // Set to False
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });

var test = new String('Test');

test.startsWith = 'New Value';
console.log(test.startsWith); // It still have the previous value in non strict mode

Enumerable -ループtrueで見られることを意味しfor in

Object.defineProperty(String.prototype, 'startsWith', {
        enumerable: true, // Set to True
        configurable: false,
        writable: false, 
        value: function(searchString, position) {
            position = position || 0;
            return this.lastIndexOf(searchString, position) === position;
        }
    });

var test = new String('Test');

for(var key in test){
   console.log(key)  ;
}

構成可能-trueこのプロパティ記述子の型が変更される可能性があり、対応するオブジェクトからプロパティが削除される可能性がある場合にのみ。

Object.defineProperty(String.prototype, 'startsWith', {
            enumerable: false,
            configurable: false, // Set to False
            writable: false, 
            value: function(searchString, position) {
                position = position || 0;
                return this.lastIndexOf(searchString, position) === position;
            }
        });

    
    delete String.prototype.startsWith; // It will not delete the property
    console.log(String.prototype.startsWith);

そして、1 つのアドバイスとして、組み込み型のプロトタイプを変更しないでください

于 2016-08-15T19:14:56.313 に答える