babel-runtime不适用于实例方法

问题描述 投票:1回答:1

我理解babel-runtime和babel-polyfill之间的区别,第一个不填充全局范围,而后者。我认为babel-runtime是更安全的hovewer我无法理解这意味着什么以及它如何影响我:

注意:诸如“foobar”.includes(“foo”)之类的实例方法将无法工作,因为这需要修改现有的内置插件(使用babel-polyfill)。

据我所知,实例方法就像map, filter, reduce,因为它们是在现有对象上调用的。 babel-runtime不会对哪个例子进行策略? :

//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,因为它应该更好,但现在我不确定什么是安全的。

javascript babeljs babel-polyfill
1个回答
1
投票

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

ES5中的等价物是这样的:

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.from(静态方法)或String.prototype.repeat(实例方法)。这就像你说的那样污染全局状态,但实例方法如:

myInstanceObj.repeat(4)

如果myInstanceObj的类型具有repeat方法,则会起作用。如果在运行时myInstanceObj是一个字符串,并且你包含了babel-polyfill,那就太好了。但是如果你正在使用babel-runtime知道myInstanceObj类型在转换时的类型(当babel转换你的代码时,为了知道如何转换,以及调用什么方法而不是方法重复)有时很棘手/这是不可能的,这就是为什么上面的实例方法有时难以通过babel-runtime && transform-runtime插件进行转换。

另一方面代码如下:

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

转换真的很容易,我们在转换时知道Array.from是来自对象Array的方法,所以在IE11中我们将使用任何....把代码放在这里......

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

© www.soinside.com 2019 - 2024. All rights reserved.