LoginSignup
6
4

More than 5 years have passed since last update.

Javascriptのin演算子とhasOwnPropertyの違い

Posted at

言語仕様を意識せずになんとなく書いていたところがあるのですが、確認してみました。
結論から述べると、

  • inはプロトタイプチェーンをたどって走査する
  • hasOwnPropertyはプロトタイプチェーンをたどらない

となります。

確認に使ったコードは下記です。
toStringはObjectが保有するプロパティ。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

property.js
// プロトタイプチェーンの確認
const myObject = {
  foo: 'prop1',
  bar: ['a', 'b', 'c'],
};

/*
  hasOwnPropertyは、対象のオブジェクトが持っているプロパティを判定する。
  プロトタイプチェーンを走査しない。
*/
console.log('[hasOwnProperty]');
console.log('foo: ', myObject.hasOwnProperty('foo')); // true
console.log('toString: ', myObject.hasOwnProperty('toString')); // false

/*
  inは、プロトタイプチェーンまで走査してプロパティの有無を判定する
*/
console.log('[in]');
console.log('foo: ', ('foo' in myObject));  // true
console.log('toString: ', ('toString' in myObject));  // true

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4