简体   繁体   English

在ES6中将类绑定到Global Scope

[英]Bind classes to Global Scope in ES6

i'm trying to recreate jQuery validator in ES6 without using any jQuery, and i've kinda hit a roadblock in trying to recreate it's functionality for adding validation methods by using the Global scope , that is if you call Validator.addMethod anywhere, it'll run the associated function in the Validator and add a method to the Validator . 我试图在ES6中 不使用任何jQuery的情况下重新创建jQuery验证器并且在尝试使用Global范围重新创建其添加验证方法的功能时遇到了障碍,也就是说,如果您在任何地方调用Validator.addMethod ,将在Validator运行关联的函数,并将方法添加到Validator

I can't seem to do this in ES6 since i'm not allowed to export my class to the Global scope, my class is never accessible from the window object , like for instance jQuery is, without this anyone who wants to add a new validation function would have to import a new function to add it class, and i cannot simply call 我似乎无法在ES6中执行此操作,因为不允许将类导出到Global范围, 无法从window对象 (例如jQuery访问我的类,没有这个人想要添加新的验证函数必须import一个新函数以添加它的类,而我不能简单地调用

Validator.addMethod('required', function(element, value){
  return value.length > 0;
})

On any file i want after loading the validator class, so my question is, is this really impossible in ES6 or am i missing something? 在加载验证器类后我想要的任何文件上,所以我的问题是,这在ES6中真的是不可能的,还是我缺少了什么? I already know it's not the best of practices and would be open to suggestions but the idea is ease of use even for people not well versed in ES6. 我已经知道这不是最佳实践,可以接受建议,但是即使对于不熟悉ES6的人来说,该想法也易于使用。

ES6 and above has been designed to avoid polluting the global scope. ES6及更高版本的设计旨在避免污染全局范围。 Your concerns are just the solution to a lot of evil bad coding practices in JavaScript . 您所关心的只是JavaScript中许多邪恶的糟糕编码实践的解决方案

BTW, you can always access window object and add a property called the same way as your class: 顺便说一句,您始终可以访问window对象并添加一个与类相同的属性:

class Validator {}

window.Validator = Validator;

...because a class is still a constructor function and prototypal inheritance wrapped by a class-based syntax. ...因为类仍然是构造函数,并且被基于类的语法包裹着原型继承。

If you're going to distribute your library both in browsers and NodeJS, you might want to do this: 如果要在浏览器和NodeJS中分发库,则可能需要这样做:

class Validator {}

var global = window || global;
global.Validator = Validator;

BTW, if you want to do things in the right way, you can distribute your library using the universal module definition. 顺便说一句,如果您想以正确的方式做事,则可以使用通用模块定义来分发您的库。 Learn more at the official GitHub repository of Universal Module Definition (UMD) . 在通用模块定义(UMD)的官方GitHub存储库中了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM