Ecmascript 6 如何在访问getter之前确定它是否已定义?

Ecmascript 6 如何在访问getter之前确定它是否已定义?,ecmascript-6,Ecmascript 6,我在JS中有一组get函数,例如: get UserName() { return this.userModel.Name; } 我想在调用函数之前检查它是否存在。 我试过: 但是它总是错误的,因为userModel.name是一个字符串,typeof UserName返回“string”类型,而不是“function” 你知道我如何做到这一点吗?检查用户名是否存在的一个简单方法是在中使用: if ('UserName' in this) { // this.UserName

我在JS中有一组get函数,例如:

get UserName() {
    return this.userModel.Name;
}
我想在调用函数之前检查它是否存在。 我试过:

但是它总是错误的,因为
userModel.name
是一个字符串,
typeof UserName
返回“string”类型,而不是“function”


你知道我如何做到这一点吗?

检查
用户名是否存在的一个简单方法是在
中使用

if ('UserName' in this) {
    // this.UserName is defined
}
如果您需要在直接访问getter函数的位置进行更强的检查,请使用:


检查
用户名
是否存在(不调用getter)的一种简单方法是在
中使用

if ('UserName' in this) {
    // this.UserName is defined
}
如果您需要在直接访问getter函数的位置进行更强的检查,请使用:


您可以使用
Object.getOwnPropertyDescriptor()
,它返回的数据结构与馈送到
Object.defineProperty()的数据结构基本相同,如下所示:

let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (descriptor && typeof descriptor.get === "function") {
   // this.UserName is a getter function
}
或者,如果您想要更精确的信息,您可以这样做:

let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (!descriptor) {
    // property doesn't exist
} else if (typeof descriptor.get === "function") {
   // this.UserName is a getter function
} else if (typeof descriptor.value === "function") {
   // property directly contains a function (that is just a regular function)
} else {
   // property exists, but it does not have a getter function and
   // is not a regular function
}

您还可以测试描述符的许多其他属性,如
可写
可配置
可枚举
,如前所述。

您可以使用
对象。getOwnPropertyDescriptor()
返回的数据结构与馈送到
对象的数据结构基本相同。defineProperty()
如下所示:

let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (descriptor && typeof descriptor.get === "function") {
   // this.UserName is a getter function
}
或者,如果您想要更精确的信息,您可以这样做:

let descriptor = Object.getOwnPropertyDescriptor(this, "UserName");
if (!descriptor) {
    // property doesn't exist
} else if (typeof descriptor.get === "function") {
   // this.UserName is a getter function
} else if (typeof descriptor.value === "function") {
   // property directly contains a function (that is just a regular function)
} else {
   // property exists, but it does not have a getter function and
   // is not a regular function
}

您还可以测试描述符的许多其他属性,如所述的
可写
可配置
可枚举

看起来像是对象文本或类中的getter,它不是函数。您可以发布一个完整的示例吗?如果您想检查属性(无论它是getter、setter还是普通数据属性),请在此
中使用
“UserName”。它看起来像对象文本或类中的getter,它不是函数。您可以发布一个完整的示例吗?如果您想检查属性(无论是getter、setter还是普通数据属性),请在此
中使用
“UserName”。您不能只使用
descriptor.get
而不是
typeof descriptor.get==“function”
?根据MDN,get
/
set
属性只能是函数或未定义。@str-可能是。为了绝对安全,我非常努力,坦率地说,我认为这更好地显示了我们期望在那里找到的东西。难道你不能使用
描述符。get
而不是
描述符的类型。get==“function”
?根据MDN,get
/
set
属性只能是函数或未定义。@str-可能是。我非常努力地确保绝对安全,坦率地说,我认为这更好地显示了我们在那里所期望的结果。