使用 Babel 扩展 ES6 中的内置原生 [英] Extending built-in natives in ES6 with Babel

查看:18
本文介绍了使用 Babel 扩展 ES6 中的内置原生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Babel 通过内置的原生数组扩展我的类

I'm using Babel for extend my class with the built-in native Array

class NewArray extends Array {
  first() {
    return this[0];
  }
}

var a = new NewArray(1, 2, 3);
console.log(a.length); // 3
console.log(a); // [ 1, 2, 3 ]
console.log(a.first()); // trigger error

在 a.first() 中,我收到此错误:

In a.first(), I'm getting this error:

console.log(a.first());
              ^ 

TypeError: a.first is not a function

我是否应该做更多的事情来扩展内置的原生?

Should I do something more to extend a built-in native?

谢谢!

推荐答案

Babel 不支持扩展原生类.它在 5.2.17 版本中被移除(参见 此提交)

Extending native classes is not supported by Babel. It was removed in version 5.2.17 (see this commit)

它被删除,因为它不能正常工作,请参阅错误:https://phabricator.babeljs.io/T1424

It was removed because it was not working properly, see the bug: https://phabricator.babeljs.io/T1424

不太可能添加它,因为它不是可以模拟的功能.我们将不得不等待浏览器的原生支持(有些已经在实验模式下支持它).这也意味着它目前在不同浏览器中的行为会有所不同.

It's unlikely it will be ever added because it's not a feature that can be simulated. We will have to wait for native support in browsers (some already support it now in experimental mode). That also means it will currently behave differently in different browsers.

这篇关于使用 Babel 扩展 ES6 中的内置原生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆