Why for ... only shows methods defined with class.prototype?

I have the following code greatly abbreviated:

class Animal {
  speak() {}
}

Animal.prototype.speaklouder = function() {};

for (const key in new Animal()) {
  console.log("key", key);
}
Run codeHide result

This gives in node 6.11.0,

key speaklouder

Why? I thought class syntax is just sugar? I expect the function will also be listed as an attribute.

+4
source share
1 answer

Class properties are not listed ; see ecma-262 6.0 14.5.14:

  • 21. For each ClassElement m in the order of the methods
  • and. If IsStatic of m is false, then
  • I am. Let the status be the result of executing a PropertyDefinitionEvaluation for m with arguments proto and false.

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

, _createClass babel:

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

+1

Source: https://habr.com/ru/post/1682120/


All Articles