大型解决方案的全局原型(JavaScript/Node) [英] Global prototypes for big solutions (JavaScript/Node)

查看:71
本文介绍了大型解决方案的全局原型(JavaScript/Node)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模块化 JavaScript 中为全局作用域编写 Array、Number 等类的原型有什么最佳实践吗?

Is there any best practice to write prototypes for classes like Array, Number, etc. for global scope in modular JavaScript?

例如,我有一个 create-react-app 应用程序,我想找到任何将原型添加到全局范围的好方法.

For example I have a create-react-app application and i want to find any good way to add prototypes to global scope.

arrayHelpers.js

Array.prototype.unique = () => {
   //... some code
};

SomeComponent.js

export default const SomeComponent = () => {
   const someArray = ["foo", "bar", "foo"];
   const someArrayThatHasOnlyUniqueItems = someArray.unique(); // ["foo", bar"]

   // ... more code 
};

我不想使用像unique(array)这样的经典函数,因为原型更简洁、更易于使用.

I don't want to use classic functions like unique(array), because prototypes are much cleaner and easier to use.

此外,将任何文件导入每个组件都不是最好的方法.

Also, importing any file into every single component is not the best way to do that.

推荐答案

扩展原生原型非常不受欢迎.这就是你打破互联网的方式!

Extending native prototypes is very frowned upon. This is how you break the internet!

您可以通过扩展现有数组类型来创建自定义数组类型(在这种情况下,您必须在需要创建一个的每个文件中导入自定义数组):

You could create a custom Array type by extending the existing one (in which case you'll have to import your custom Array in every file you need to create one):

class MyArray extends Array {
  function unique() {
    //...
  }
}
const someArray = new MyArray("foo", "bar")

您可以扩展 Array 的 Symbols 原型(在这种情况下,您必须在需要使用该函数的每个文件中导入您的 Symbol):

You could extend the Symbols prototype of Array (in which case you'll have to import your Symbol in every file you need to use the function):

const unique = new Symbol('unique')
Array.prototype[unique] = () => { ... }
// ...
someArray[unique]()

但可能最好的方法是简单地使其成为一个纯粹的独立函数:

But probably the best way to do it would be to simply make it a pure standalone function:

function unique(array) {
  // ...
}
unique(someArray)

是的,这很无聊,就像大多数好的代码一样.

Yes it is boring, like most good code should be.

是的,它没有那么甜(但如果你喜欢甜食,你可以随时编写自己的 Babel 插件).

Yes it isn't as sugary (but if you like sugar, you could always write your own Babel plugin).

是的,你必须在任何地方导入它(大多数 JS 项目在每个文件上都有很多导入).

Yes you have to import it everywhere (most JS projects have a lot of imports on every file).

是的,这就是这样做的方法.

Yes this is the way to do it.

这篇关于大型解决方案的全局原型(JavaScript/Node)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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