LoginSignup
4
4

More than 5 years have passed since last update.

[JavaScript] プロパティ確認のメソッドなどが継承追ったり列挙不能も考慮するか

Last updated at Posted at 2014-03-21

プロパティ確認のメソッドなどが継承追ったり列挙不能も考慮するか の自分用メモ

  • 2015/08/22
    • 廃止された for each-in を削除
    • for-of を追加し、Iterator とまとめる
列挙可能のみ 列挙不能も
自身のみ
継承追う

① 自身のみ 列挙可能のみ

  • Object#propertyIsEnumerable(key) ... 真偽値
  • Object.keys(obj) ... 配列
  • for-of Iterator(obj) ... key, value のループ
  • for-of Iterator(obj, true) ... key のループ

② 自身のみ 列挙不能も

  • Object#hasOwnProperty(key) ... 真偽値
  • Object.getOwnPropertyNames(obj) ... 配列

③ 継承追う 列挙可能のみ

  • for-in ... propのループ

④ 継承追う 列挙不能も

  • ドットアクセス(.)・ブラケットアクセス([ ]
  • in 演算子 ... 真偽値

確認

var parent = {};
var obj = Object.create(parent);
Object.defineProperties(parent, {
  'parent2': { value: 'p2', enumerable: false },
  'parent1': { value: 'p1', enumerable: true },
});
Object.defineProperties(obj, {
  'self2': { value: 's2', enumerable: false },
  'self1': { value: 's1', enumerable: true },
});

// ① 自身のみ 列挙可能のみ
obj.propertyIsEnumerable('no'); //=> false
obj.propertyIsEnumerable('parent2'); //=> false
obj.propertyIsEnumerable('parent1'); //=> false
obj.propertyIsEnumerable('self2'); //=> false
obj.propertyIsEnumerable('self1'); //=> true
Object.keys(obj); //=> ['self1']
for(let key of Iterator(obj, true)) console.log(key); //=> 'self1'
for(let[key, val] of Iterator(obj)) console.log(key, val); //=> 'self1' 's1'

// ② 自身のみ 列挙不能も
obj.hasOwnProperty('no'); //=> false
obj.hasOwnProperty('parent2'); //=> false
obj.hasOwnProperty('parent1'); //=> false
obj.hasOwnProperty('self2'); //=> true
obj.hasOwnProperty('self1'); //=> true
Object.getOwnPropertyNames(obj); //=> ['self2', 'self1']

// ③ 継承追う 列挙可能のみ
for(let key in obj) console.log(key); //=> 'self1', 'parent1'

// ④ 継承追う 列挙不能も
'no' in obj; //=> false
'parent2' in obj; //=> true
'parent1' in obj; //=> true
'self2' in obj; //=> true
'self1' in obj; //=> true
4
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
4
4