LoginSignup
1
1

More than 5 years have passed since last update.

開眼!JavaScriptの2.6・2.7のまとめ hasOwnProperty()とin演算子について

Last updated at Posted at 2015-04-12

開眼!JavaScriptの2.6と2.7のまとめです。

2.6 hasOwnProperty()を使って、プロパティがプロトタイプチェーン経由ではないことを確認

2.7 in演算子を使って、オブジェクトがプロパティを保持しているかどうかを確認する

in演算子は、オブジェクトが指定された名前のプロパティを保持しているかを確認する。
しかしin演算子は、指定したオブジェクト自身が持つプロパティがだけでなくプロトタイプチェーン上で見つかるプロパティの存在も結果をtrue(プロパティを保持している)として返す。
指定したオブジェクト自身が持つプロパティだけを確認する場合はhasOwnProperty()を使用する。

in演算子を使って、そのオブジェクトが持つプロパティかを確認。

var myObject = {foo:'value'};
console.log('foo' in myObject);

console.log('toString' in myObject);

結果
true
true →toStringはmyObjectで定義されていないがプロトタイプチェーン上で見つかるプロパティのためtrueになる。

hasOwnProperty()を使って、そのオブジェクト自身が持つプロパティかを確認。

var myObject = {foo:'value'};
console.log(myObject.hasOwnProperty('foo'));

console.log(myObject.hasOwnProperty('toString'));

結果
true
false →toStringはmyObject自身が保持しているプロパティではないためfalseになる。

ちなみにhasOwnProperty()自身は、プロトタイプチェーン上(Object.prototype)で見つかるプロパティのため下記のような結果になる。

var myObject = {foo:'value'};
console.log('hasOwnProperty' in myObject);

console.log(myObject.hasOwnProperty('hasOwnProperty'));

結果
true
false

1
1
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
1
1