原型对象缺少实例方法



在声明类(使用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

Object.keys仅显示枚举属性。class在原型上定义的属性无法枚举。

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

您可以使用 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((方法返回所有属性的数组(包括非可启用属性,直接在给定对象上找到的除外(。

class语法中定义的类方法是不可启示的,这就是为什么bObject.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}

最新更新