【问题标题】:Instance methods missing from prototype object原型对象中缺少实例方法
【发布时间】:2018-02-13 09:57:20
【问题描述】:

在声明类时(使用 ECMAScript 2015 class)语法,定义为类的一部分的方法存储在哪里?我期待在原型对象上找到它们,但由于某种原因,我无法在以下示例中访问它们:

class MyClass {
  constructor() {
    this.a = function() {return ("a");};
  }

  b() { return ("b"); }
}

MyClass.prototype.c = function() { return ("c"); }

const m = new MyClass();

// Sanity check: All three functions are callable and return correct results
console.log(m.a()); // "a"
console.log(m.b()); // "b"
console.log(m.c()); // "c"

// Expected: The only property of the object m itself is a
console.log(Object.keys(m)); // ["a"]

// Unexpected: Where is b?
console.log(Object.keys(Object.getPrototypeOf(m))); // ["c"]
console.log(Object.keys(MyClass.prototype)); // ["c"]

b-函数必须在某个地方(它显然是可调用的),但在哪里?我测试了这种行为node 9.5.0Firefox 58.0.1

【问题讨论】:

    标签: javascript ecmascript-6 prototype


    【解决方案1】:

    Object.keys 只显示可枚举的属性。 class 在原型上定义的属性不可枚举。

    console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(m)));
    

    【讨论】:

      【解决方案2】:

      您可以使用getOwnPropertyNames() 方法返回所有属性:

      class MyClass {
        constructor() {
          this.a = function() {
            return ("a");
          };
        }
      
        b() {
          return ("b");
        }
      }
      
      MyClass.prototype.c = function() {
        return ("c");
      }
      
      const m = new MyClass();
      
      // Sanity check: All three functions are callable and return correct results
      console.log(m.a()); // "a"
      console.log(m.b()); // "b"
      console.log(m.c()); // "c"
      
      // Expected: The only property of the object m itself is a
      console.log(Object.keys(m)); // ["a"]
      
      // Unexpected: Where is b?
      console.log(Object.keys(Object.getPrototypeOf(m))); // ["c"]
      console.log(Object.keys(MyClass.prototype)); // ["c"]
      console.log(Object.getOwnPropertyNames(MyClass.prototype));

      Object.getOwnPropertyNames() 方法返回直接在给定对象上找到的所有属性(包括不可枚举的属性,使用 Symbol 的属性除外)的数组。

      【讨论】:

      • 我不认为 OP 想知道 如何 显示 b,他只是想知道 为什么 它没有出现.
      • @Alnitak,在可运行的 sn-p 末尾,我添加了来自 MDN 站点的引用,并突出显示了与用户问题相关的部分。我认为我不能比实际的文档更清晰。
      【解决方案3】:

      class 语法中定义的类方法是不可枚举的,这就是b 不出现在Object.keys 的输出中的原因:

      > Object.getOwnPropertyDescriptor(MyClass.prototype, "b")
      {value: ƒ, writable: true, enumerable: false, configurable: true}
      
      > Object.getOwnPropertyDescriptor(MyClass.prototype, "c")
      {value: ƒ, writable: true, enumerable: true, configurable: true}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 2013-03-24
        相关资源
        最近更新 更多