【问题标题】:Where are the methods in object created using class in Javascript使用Javascript中的类创建的对象中的方法在哪里
【发布时间】:2021-04-12 11:43:04
【问题描述】:

假设有一个类同时具有属性和方法。当使用 new 关键字从这个类创建对象并假设在控制台上打印时,它只显示对象中的属性名称,为什么现在显示方法?我可以访问代码中的方法。

示例代码,

class A {
  propA = true;
  methodA() { return true; }
  methodB() { return true; }
}

console.log("Object of A -> ", new A());
// Object of A ->  A { propA: true }

附:我正在使用打字稿

【问题讨论】:

  • a) 它们是不可枚举的 b) 它们是从原型继承的。 new A 不创建任何方法。

标签: javascript class object


【解决方案1】:

你需要访问原型,然后获取属性

此处的示例代码:

class A {
  propA = true;
  methodA() { return true; }
  methodB() { return true; }
}

console.log("Object of A -> ", Object.getOwnPropertyNames(Object.getPrototypeOf(new A())));
//Object of A -> ["constructor", "methodA", "methodB"]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多