【发布时间】: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.0 和Firefox 58.0.1
【问题讨论】:
标签: javascript ecmascript-6 prototype