0

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"]

これは可能ですか?

また、反対のことをしてフィールドを返すことはできますか?

4

2 に答える 2

1

できることは 2 つあります (正確な状況によっては、それ以上のこともあるかもしれません)。

  1. 「プライベート」プロパティに別の名前を付けます。たとえば、末尾にアンダースコアを付けて、プロパティを反復処理する (および除外する) ときに、プロパティ名がアンダースコアで終わるかどうかを確認します。

  2. 「実際のプロパティ」とは、プロトタイプで定義されたプロパティを意味し、オブジェクト自体で定義されたすべてのプロパティを無視したい場合は、 を使用.hasOwnPrototypeして定義されている場所を確認できます。Object.getPrototypeOfまたは、プロトタイプのプロパティのみを使用して反復することもできます。

于 2013-05-17T16:37:41.293 に答える
0

悪いコード。その後の議論が他の誰かを助けるかもしれないので、私は(コメントを付けて)残します.

常に defineProperty() を使用して列挙不可能なプロパティを取得する場合、これは機能します。

function GetProperties(obj) {
    var result = [];
    for (var prop in obj) {
        // propertyIsEnumerable() returns false just because the properties
        // are inherited thru the prototype chain. It was just a coincidence
        // that it got the desired result. Don't do this.
        if (typeof obj[prop] !== "function" && !obj.propertyIsEnumerable(prop)) {
            result.push(prop);
        }
    }
    return result;
}

そうでなければ、問題の一般的な解決策を知りたいです。

編集:コードがenumerable: trueあり、それでも私のコードは尋ねられたことを正確に実行していることがわかります。ダブルユーティーエフ?

于 2013-05-17T16:41:30.170 に答える