代码之家  ›  专栏  ›  技术社区  ›  Tomasz Mularczyk

babel runtime在实例方法上不起作用

  •  2
  • Tomasz Mularczyk  · 技术社区  · 7 年前

    map, filter, reduce

    //1
    ['aa', 'bb', 'cc'].forEach(console.log);
    
    //2
    const arr = ['aa', 'bb', 'cc'];
    arr.forEach(console.log);
    
    //3
    const entries = Object.entries(someObj).filter(([key, value]) => key.startsWith('hello'));
    
    //4
    const map = new Map();
    
    //5
    var s = new Set(["foo", window]);
    Array.from(s);   
    

    如何准确识别实例方法?

    我在我的babel runtime项目中替换了babel polyfill,因为它应该更好,但现在我不确定什么是安全的。

    1 回复  |  直到 7 年前
        1
  •  1
  •   dalvarezmartinez1    7 年前

    Here 解释Javascript中静态方法与实例方法的链接。

    基本上:

    class SomeClass {
       instancMethod() {
        return 'Instance method has been called';
       }
    
       static staticMethod() {
         return 'Static method has been called';
       }
    }
    // Invoking a static method
    SomeClass.staticMethod(); // Called on the class itself
    // Invoking an instance method 
    var obj = new SomeClass();
    obj.instanceMethod(); // Called on an instance of the class
    

    function SomeClass() {
       this.prototype.instanceMethod = function() {
          return 'Instance method has been called';
       }
    }
    SomeClass.staticMethod = function() {
       return 'Static method has been called';
    }
    // And the invocations:
    SomeClass.staticMethod();
    new SomeClass().instanceMethod();
    

    例如,当您在IE11中使用babel polyfill时,所有不存在的ES2015+方法都已定义,例如Array。来自(静态方法)或字符串。原型重复(实例方法)。正如你所说,这正在污染全球国家,但实例方法如下:

    myInstanceObj.repeat(4)
    

    如果myInstanceObj的类型具有repeat方法,则将工作。如果在运行时myInstanceObj是一个字符串,并且您包含了babel多边形填充,那么很好。但是,如果您正在使用babel运行时,在传输时知道myInstanceObj类型(当babel转换代码时,为了知道如何转换,以及调用什么方法而不是方法重复),有时会很棘手/不可能,这就是为什么像上面这样的实例方法有时很难通过babel运行时转换的原因&transform runtime插件。

    另一方面,代码如下:

    Array.from([1, 2, 3], x => x + x);
    

    真的很容易变换,我们知道在传输时那个数组。from是来自对象数组的方法,因此在IE11中,我们将使用任何。。。。在此处放置代码。。。

    如果我们使用babel polyfill,这个方法已经存在了,因为添加这个方法的全局范围受到了污染,所以一切又好了。这完全取决于你需要什么。