简体   繁体   中英

function _inherits babel after transpiling

Hello I'm not good at English. But I can not get an answer to the question... I have some code ES2015:

class Animal{}
class Rabbit extends Animal{}

After transpiling this code I get function _inherits. I just can not understand what the last expression does:

if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;

In my opinion, the last but one does the same. Together:

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

The code basically calls Object.setPrototypeOf (ES6) and falls back to __proto__ for preES6 browsers. That fall back is not the default as __proto__ is a property that shouldn't actually exist. It was added to the spec to create consistency between browsers, Chrome added it as an "experimental, don't do this", then it was added to the spec as it was commonly used. With __proto__ however you can break a lot of things, not to mention every optimization the browser could make:

 Function.prototype.__proto__ = new Proxy({}, { get(k){ return "test" } });

 console.log((function() { }).t);

therefore using __proto__ causes some trouble for the browser as it has to rollback nearly all optimizations. Object.setPrototypeOf however was added purposely to the language and has a more strict, and therefore non-risky usage, using it will break some optimizations but not all, therefore it is much better to use this if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM