の hasOwnProperty() JavaScript のメソッドは、プロトタイプ チェーンから継承されるのではなく、オブジェクトに直接属する特定のプロパティがあるかどうかを確認するのに便利です。これは、オブジェクトが独自のプロパティを持っているかどうかを確認するのに便利なツールです。
構文:
object.hasOwnProperty( prop );>
パラメーター :
- 小道具: テストするプロパティの名前を文字列またはシンボルの形式で保持します。
戻り値:
オブジェクトが指定されたプロパティを独自のプロパティとして持っているかどうかを示すブール値を返します。
例 1: この例では、オブジェクトのプロパティをチェックします。
JavaScript function checkProperty() { let exampleObj = {}; exampleObj.height = 100; exampleObj.width = 100; // Checking for existing property result1 = exampleObj.hasOwnProperty('height'); // Checking for non-existing property result2 = exampleObj.hasOwnProperty('breadth'); console.log(result1); console.log(result2); } checkProperty()> 出力
true false>
例 2: この例では、クラスのオブジェクトのプロパティをチェックします。
JavaScript function checkProperty() { function Car(a, b) { this.model = a; this.name = b; } let car1 = new Car('Mazda', 'Laputa'); // Checking for existing property result1 = car1.hasOwnProperty('model'); // Checking for non-existing property result2 = car1.hasOwnProperty('wheels'); console.log(result1); console.log(result2); } checkProperty()> 出力
true false>
オブジェクト メソッドとそれらを確認するためのプロパティの完全なリストがあります。これを参照してください。 JavaScript オブジェクトの完全なリファレンス 記事。
サポートされているブラウザ:
- Google Chrome 1以降
- Firefox 1 以降
- Internet Explorer 5.5以降
- エッジ 12 以降
- Safari 3以降
- Opera 5 以降