编译后的函数_inherits babel

时间:2018-10-13 14:11:25

标签: javascript

你好,我英语不好。但是我找不到这个问题的答案... 我有一些代码ES2015:

class Animal{}
class Rabbit extends Animal{}

在编译这段代码后,我得到了函数_inherits。 我只是不明白最后一个表达式的作用:

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

在我看来,最后一个是一样的。一起:

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;
}

1 个答案:

答案 0 :(得分:0)

该代码基本上会调用Object.setPrototypeOf(ES6),而对于preES6浏览器则会退回到__proto__。后退不是默认值,因为__proto__是实际上不应该存在的属性。它被添加到规范中以创建浏览器之间的一致性,Chrome将其添加为“实验性的,不要这样做”,然后将其添加到规范中,因为它通常被使用。但是,使用__proto__可以打破很多事情,更不用说浏览器可以进行的所有优化:

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

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

因此,使用__proto__会对浏览器造成一些麻烦,因为它必须回滚几乎所有优化。 Object.setPrototypeOf是故意添加到该语言中的,它具有更严格的用法,因此使用的是非风险的,使用它会破坏一些优化,但不是全部,因此使用它会更好如果可能的话。