[英]Confusion about JavaScript Object's method being non-enumerable
class RandomObject {
constructor() {
this.method1 = function() {}
}
method2() {
// only this is non enumerable
}
method3 = function() {}
}
const object = new RandomObject()
for (const prop in object) {
console.log(prop) // 'method1', 'method2'
}
我发现在for...in
循环中只有method1
和method2
被打印出来,这意味着它们是可枚举的。 但是method2
没有出现在循环中,这意味着它是不可枚举的。 我想知道是什么导致了这里的差异? 为什么在这种情况下只有method2
是不可枚举的?
另外,我发现如果我直接在 object 文字中定义方法,那么它又是可枚举的:
const object2 = {
method2() {
// Now this is enumerable
}
}
Class 原型方法是不可枚举的——这正是语法的设计方式:
class X { method() { } } console.log(Object.getOwnPropertyDescriptor(X.prototype, 'method').enumerable);
请参阅ClassDefinitionEvaluation中的CreateMethodProperty ,它要求 class 方法是不可枚举的。
相比之下,class 字段语法——即直接在 class 主体内的someProperty = someExpression
是在构造函数内运行this.someProperty = someExpression
的语法糖。 对 object 上不存在的属性的普通分配会导致该属性是可枚举的。
class RandomObject {
method3 = function() {}
}
相当于
class RandomObject {
constructor() {
this.method3 = function() {}
}
}
对于普通对象的方法,请参阅PropertyDefinitionEvaluation ,它描述了如何在 object 文字中创建属性(包括方法)。 它会执行
返回? MethodDefinition 使用 arguments object 和可枚举的 MethodDefinition 评估。
其中enumerable
已使用ObjectLiterals设置为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.