如何判断 ES6 类是否有给定名称的 getter?

use*_*110 5 javascript ecmascript-6

看起来 ES6 类并不像人们预期的那样响应 .hasOwnProperty 。

如果你有这门课:

class Foo {
  get index() {
    return 12;
  }
}
Run Code Online (Sandbox Code Playgroud)

此代码将返回 false:

let myFoo = new Foo();
alert(myFoo.hasOwnProperty("index"); <-- alerts "false"
Run Code Online (Sandbox Code Playgroud)

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

class Foo {
  get index() {
    return 12;
  }
  get position() {
    return undefined;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

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