节点:使用 "Class" 语法的原型不显示预期的对象
Node: prototype using "Class" syntax does not show expected object
在 JS 中,如果我使用构造函数创建一个新对象,并且访问原型对象,我可以看到原型具有的任何 属性。 (在代码中会更清楚):
function F() {
this.attr = 42;
}
F.prototype.foo = function() {
return 'life';
}
$> let f = new F();
undefined
$> f
F { attr: 42 }
$> Object.getPrototypeOf(f)
F { foo: [Function] }
这里一切正常
现在,我将使用 class 语法来创建相同的场景
class C {
constructor() {
this.attr = 42;
}
foo() {
return 'life';
}
}
$> let c = new C()
undefined
$> c
C { attr: 42 }
$> Object.getPrototypeOf(o)
C {}
结果 C {}
让我很困惑。 我的 foo
属性在哪里? 它不在 c
对象中,但似乎也不在我的 C
原型中!
问题很可能是您的控制台在显示对象时不包含不可枚举的属性。
在第一种情况下,您通过赋值创建属性,因此它们是可枚举的:
Object.getOwnPropertyDescriptor(F.prototype, 'foo').enumerable; // true
但在第二种情况下他们不是
Object.getOwnPropertyDescriptor(C.prototype, 'foo').enumerable; // false
这就是为什么你永远不应该相信控制台中的对象表示。如果你想列出一个对象的所有自身属性,这可能会起作用:
Object.getOwnPropertyNames(C.prototype); // [ "constructor", "foo" ]
如果您的控制台也无法正确显示阵列,您可能想要加入该阵列。
在 JS 中,如果我使用构造函数创建一个新对象,并且访问原型对象,我可以看到原型具有的任何 属性。 (在代码中会更清楚):
function F() {
this.attr = 42;
}
F.prototype.foo = function() {
return 'life';
}
$> let f = new F();
undefined
$> f
F { attr: 42 }
$> Object.getPrototypeOf(f)
F { foo: [Function] }
这里一切正常
现在,我将使用 class 语法来创建相同的场景
class C {
constructor() {
this.attr = 42;
}
foo() {
return 'life';
}
}
$> let c = new C()
undefined
$> c
C { attr: 42 }
$> Object.getPrototypeOf(o)
C {}
结果 C {}
让我很困惑。 我的 foo
属性在哪里? 它不在 c
对象中,但似乎也不在我的 C
原型中!
问题很可能是您的控制台在显示对象时不包含不可枚举的属性。
在第一种情况下,您通过赋值创建属性,因此它们是可枚举的:
Object.getOwnPropertyDescriptor(F.prototype, 'foo').enumerable; // true
但在第二种情况下他们不是
Object.getOwnPropertyDescriptor(C.prototype, 'foo').enumerable; // false
这就是为什么你永远不应该相信控制台中的对象表示。如果你想列出一个对象的所有自身属性,这可能会起作用:
Object.getOwnPropertyNames(C.prototype); // [ "constructor", "foo" ]
如果您的控制台也无法正确显示阵列,您可能想要加入该阵列。