for in文はオブジェクト内のプロパティ名を取り出す。取り出される値は関数やプロトタイプチェーン上に定義された値も含まれる。
for in文のポイントをまとめる。
var Hoge= function () {
this.name= 'Hoge Property';
this.getName = function () {
return this.name;
};
};
Hoge.prototype.protoName = 'Hoge Protptype Property';
Hoge.prototype.protoGetName = function () {
return this.protoName;
}
var Foo = function () {
this.my = 'Foo Property';
}
var hoge = new Hoge();
var foo = new Foo();
var p;
for (p in hoge) {
foo[p] = hoge[p];
}
for (p in foo) {
console.log(name);
}
// 実行結果 順序は保証されない
// my
// name
// getName
// protoName
// protoGetName
for in文はプロパティだけでなく関数(メソッド)も取り出す。関数を除外する場合は下記のように修正する。
var Hoge= function () {
this.name= 'Hoge Property';
this.getName = function () {
return this.name;
}
}
Hoge.prototype.protoName = 'Hoge Protptype Property';
Hoge.prototype.protoGetName = function () {
return this.protoName;
}
var Foo = function () {
this.my = 'Foo Property';
}
var hoge = new Hoge();
var foo = new Foo();
var name;
for (name in hoge) {
if (typeof hoge[name] !== 'function') {
foo[name] = hoge[name];
}
}
for (name in foo) {
console.log(name);
}
// 実行結果 順序は保証されない
// my
// name
// protoName
var Hoge= function () {
this.name= 'Hoge Property';
this.getName = function () {
return this.name;
}
}
Hoge.prototype.protoName = 'Hoge Protptype Property';
Hoge.prototype.protoGetName = function () {
return this.protoName;
}
var Foo = function () {
this.my = 'Foo Property';
}
var hoge = new Hoge();
var foo = new Foo();
var name;
for (name in hoge) {
foo[name] = hoge[name];
}
for (name in foo) {
if (Foo.hasOwnProperty(name)) {
console.log(name);
}
}
// 実行結果 順序は保証されない
// name
// foo.hasOwnProperty(name)の場合はすべてのプロパティとメソッドを表示する。
[1] DontEnum属性は内部で設定され外部からは変更できない(ECMA-262 3rd ECMA-262 5thではenumerableを使って設定できる)。Object.prototype.toString, Object.prototype.hasOwnPropertyなどがfor in文で抽出されないのはDontEnum属性が設定されているから。
[2] Object.prototypeのプロパティは下記のものがある。Object.prototype.toString, Object.prototype.toLocaleString, Object.prototype.valueOf, Object.prototype.hasOwnProperty, Object.prototype.isPrototypeOf, Object.prototype.propertyIsEnumerable。
Christian Johansen著 長尾高広訳 『テスト駆動 JavaScript』(p139) ASCII。
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。