我有以下代码,大大减少了:
class Animal {
speak() {}
}
Animal.prototype.speaklouder = function() {};
for (const key in new Animal()) {
console.log("key", key);
}
这会在节点 6.11.0 中产生,
key speaklouder
这是为什么?我认为类语法只是糖?我希望函数 speak 也被列为一个属性。
最佳答案
类属性是 不可枚举的 ,参见 ecma-262 6.0 14.5.14:
http://www.ecma-international.org/ecma-262/6.0/#sec-runtime-semantics-classdefinitionevaluation
PropertyDefinitionEvaluation
的第二个参数是 enumerable
:http://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions-runtime-semantics-propertydefinitionevaluation
例如,您可以检查 babel 输出中的
_createClass
函数:function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
// ...
descriptor.enumerable = descriptor.enumerable || false;
// ...
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
// ...
return Constructor;
}
_createClass(Animal, [{
key: "speak",
value: function speak() {}
}]);
https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Cstage-2&targets=&browsers=&builtIns=false&debug=false&code_lz=MYGwhgzhAECCB2BLAtmE0DeBYAUNaEADgKZgDWAFAJSYC-u9OuCKaAdIQE4D2ALnwE8SbIqTIhuAVwAmxTtAC80AGaT4wXom7xqdANy5cy7vIrBtEXtDLEB0RPGjxiAdzhJUIajWx5o5-AhuEGI2CQBzCgAiGwEogBprWyoDHEYgA
看:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
关于javascript - 为什么 for ... in 只显示用 class.prototype 定义的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45280661/