原型对象中缺少实例方法

时间:2018-02-13 09:57:21

标签: javascript ecmascript-6 prototype

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

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

3 个答案:

答案 0 :(得分:2)

Object.keys仅显示可枚举的属性。 <{1}}在原型上定义的属性不可枚举。

class

答案 1 :(得分:1)

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}

答案 2 :(得分:1)

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

&#13;
&#13;
window.onbeforeunload = (event) => {
        if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
            event.preventDefault();
        }
    };
&#13;
&#13;
&#13;

  

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