Skip to content

Instantly share code, notes, and snippets.

@foomin10
Last active August 29, 2015 13:57
Show Gist options
  • Save foomin10/9688895 to your computer and use it in GitHub Desktop.
Save foomin10/9688895 to your computer and use it in GitHub Desktop.
[JavaScript] プロパティ確認のメソッドなどが継承追ったり列挙不能も考慮するか ref: http://qiita.com/MizuiroFolder/items/5735296534dabb10d1a5
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment