簡體   English   中英

Javascript / Typescript - 獲取對象屬性可見性和類型

[英]Javascript / Typescript - get object property visibility and type

我的問題:

我需要區分typescript類的private,public和getter(get X())屬性。

我的項目:

我有一個Angular項目,它有一個模型設計模式。 阿卡。 用戶模型看起來像這樣

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }
}

要將這些模型發送到后端,我只是JSON.stringify()它們,如果用戶id設置為13,則返回一個這樣的對象

{
    _id: 13
}

現在我需要修改UserModel上的toJSON()函數,這樣我將返回get X()變量,而不是返回對象的私有屬性。 輸出應該如下所示。

{
    id: 13
}

我創建了這個簡單的函數,以檢索對象的所有屬性,但這給了我私有屬性和get屬性。

abstract class BaseModel {
    public propsToObj() : {[key: string]: any} {
        let ret: any = {};

        for (var prop in this) {
            ret[prop] = this[prop];
        }

        return ret;
    }
}

並且toJSON函數看起來像這樣

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }

    toJSON() {
        return this.propsToObj();
    }
}

字符串化UserModel的結果如下所示

{
    _id: 13,
    id: 13
}

總之,我需要知道類的屬性的可見性和類型(getter或常規變量?),我將如何實現這一目標?

你的propsToObj()工作錯誤,它只獲取所有屬性,你需要更改它以便它只獲得getter,例如你可以使用它

abstract class BaseModel {
    public propsToObj() : {[key: string]: any} {
      let ret: any = {};

      for (const prop in this) {
        const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
        if (descriptor && typeof descriptor.get === 'function') {
            ret[prop] = this[prop];
        }
      }
        return ret;
    }
}

Object.getOwnPropertyDescriptor將獲取一個屬性的描述符,你可以從中檢查描述符中是否有get函數,如果是你的屬性是getter,如果不是常規屬性,你可以在這里閱讀更多關於描述符的內容MDN(描述符)

你提出的最后一個問題

我需要知道類的屬性的可見性和類型,我將如何實現這一目標?

據我所知,你無法獲得屬性的可見性,對於類型,如果你想知道屬性的數據類型,你可以使用typeof

在propsToObj()方法中的示例:

public propsToObj() : {[key: string]: any} {
      let ret: any = {};

      for (const prop in this) {
        const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
        if (descriptor && typeof descriptor.get === 'function') {
            ret[prop] = this[prop];
            console.log(typeof ret[prop]); // just exaple how you can know type you can save it with property too if you need it
        }
      }
        return ret;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM