微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 检查typescript类是否有setter/getter

我有一个typescript类,它具有以下属性
export class apiAccount  {
    private _balance : apiMoney;
    get balance():apiMoney {
        return this._balance;
    }
    set balance(value : apiMoney) {
        this._balance = value;
    }

    private _currency : string;
    get currency():string {
        return this._currency;
    }
    set currency(value : string) {
        this._currency = value;
    }
    ...

我需要创建这个类的空白实例:

let newObj = new apiAccount();

然后检查它是否具有“货币”的设置器.
我认为这正是getownPropertyDescriptor所做的,但显然我错了:

Object.getownPropertyDescriptor(newObj,'currency')
Object.getownPropertyDescriptor(newObj,'_currency')

这两个都返回undefined.但铬似乎做到了!当我将鼠标悬停在实例上时,它会向我显示属性,并将它们显示为未定义.如何获取这些属性名称的列表,或检查对象中是否存在属性描述符?

解决方法

“问题”是Object.getownPropertyDescriptor – 顾名思义 – 只返回对象自己的属性的描述符.即:只有直接分配给该对象的属性,而不是来自其原型链中某个对象的属性.

在您的示例中,货币属性在apiAccount.prototype上定义,而不是在newObj上定义.以下代码段演示了这一点:

class apiAccount {
    private _currency : string;
    get currency():string {
        return this._currency;
    }
    set currency(value : string) {
        this._currency = value;
    }
}

let newObj = new apiAccount();
console.log(Object.getownPropertyDescriptor(newObj,'currency')); // undefined
console.log(Object.getownPropertyDescriptor(apiAccount.prototype,'currency')); // { get,set,... }

如果要在对象的原型链中的任何位置找到属性描述符,则需要使用Object.getPrototypeOf进行循环:

function getPropertyDescriptor(obj: any,prop: string) : PropertyDescriptor {
    let desc;
    do {
        desc = Object.getownPropertyDescriptor(obj,prop);
    } while (!desc && (obj = Object.getPrototypeOf(obj)));
    return desc;
}

console.log(getPropertyDescriptor(newObj,... }

原文地址:https://www.jb51.cc/js/156899.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐