JavaScript でのプロパティ リフレクションのコードのこの小さなスニペットに出くわしました。
function GetProperties(obj) {
var result = [];
for (var prop in obj) {
if (typeof obj[prop] !== "function") {
result.push(prop);
}
}
return result;
}
次の「CustomObject」を使用してテストしました。
var CustomObject = (function () {
function CustomObject() {
this.message = "Hello World";
this.id = 1234;
}
Object.defineProperty(CustomObject.prototype, "Foo", {
get: function () {
return "foo";
},
enumerable: true,
configurable: true
});
Object.defineProperty(CustomObject.prototype, "Bar", {
get: function () {
return "bar";
},
enumerable: true,
configurable: true
});
return CustomObject;
})();
jQuery を使用した簡単なテストを次に示します。
$(document).ready(function () {
console.log(GetProperties(new CustomObject()));
});
結果は次のとおりです。
["message", "id", "Foo", "Bar"]
GetProperties 関数は、関数ではない入力オブジェクト内のすべての配列を返すだけであることを理解していますが、結果をフィルタリングして「実際の」プロパティのみを取得したいので、出力は次のようになります。
["Foo", "Bar"]
これは可能ですか?
また、反対のことをしてフィールドを返すことはできますか?