Barbu Barbu Barbu Barbu - 1 year ago 82
Javascript Question

Babeljs way of transpiling es6 class extension

I was playing a bit with Babel and ES6, transpiling some code and I was stucked at this part:

class App extends SomeParent {
myFunction() {

}
}


The output that I'm interested in, is this:

var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();


My question is why they used this way/method for
_createClass
var of using IIF and then returing another function instead doing something like this:

var _createClass = function (Constructor, protoProps, staticProps) {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
}


without having to use IIF and return another function...

Is there a good reason/practice?

Link for babel demo here

Answer Source

Babel's current output will only create the defineProperties once wheras your example will recreate the function for ever single class declaration.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download