【问题标题】:How to tell if an ES6 class has a getter of given name?如何判断 ES6 类是否具有给定名称的 getter?
【发布时间】:2019-12-10 21:57:34
【问题描述】:

似乎 ES6 类没有像预期的那样响应 .hasOwnProperty。

如果你有这个课程:

class Foo {
  get index() {
    return 12;
  }
}

此代码将返回 false:

let myFoo = new Foo();
alert(myFoo.hasOwnProperty("index"); <-- alerts "false"

我可以测试一个属性是否返回“未定义”,但这不会区分返回未定义的“获取”和没有具有给定名称的方法的类对象,即

class Foo {
  get index() {
    return 12;
  }
  get position() {
    return undefined;
  }
}

在 ES6 类上测试“getter”或“setter”是否存在的正确方法是什么?

【问题讨论】:

  • 不要在Javascript中使用类,你不会有这个问题:)
  • 好的,感谢第一个似乎并没有完全做到这一点,但 MDN 页面建议这样做: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(myFoo), 'index');这有点麻烦,但至少有效。
  • 是的,如果我也使用 ruby​​,我想我不会有这个问题。

标签: javascript ecmascript-6


【解决方案1】:

JavaScript 中的类有点奇怪,因为它基本上只是原型继承。所以在这种情况下,index应该存在于myFoo的原型上:

class Foo {
  get index() {
    return 12;
  }
}
const myFoo = new Foo();
myFoo.hasOwnProperty('index'); // false
Object.getPrototypeOf(myFoo).hasOwnProperty('index'); // true

【讨论】:

  • 测试setter是否存在?
  • 有专门用于查找 getter/setter 的函数,例如myFoo.__lookupSetter__('index'),但它们已被弃用。我相信您最好的选择是使用Object.getOwnPropertyDescriptor 来区分getter 和setter。
  • 谢谢。值得注意的是,您上面描述的内容适用于类实例,不适用于计划 javascript 对象。所以如果你想要一个像这样的功能
【解决方案2】:

作为@zero298 链接;

Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'index').get

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多