在ES6中将类绑定到Global Scope [英] Bind classes to Global Scope in ES6

查看:21
本文介绍了在ES6中将类绑定到Global Scope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ES6 中重新创建jQuery验证程序,而没有使用任何jQuery,我在尝试重新创建其添加验证方法功能时遇到了障碍通过使用 Global scope ,也就是说,如果您在任何地方调用 Validator.addMethod ,它将在 Validator 中运行关联的函数并添加一个 Validator 的方法.

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中执行此操作,因为不允许将类导出到Global范围,我的类从窗口对象中无法访问,例如 jQuery 是,没有这个,想要添加新验证功能的任何人都必须 import 一个新函数将其添加到类中,而我不能简单地调用

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

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

在加载验证器类之后我想要的任何文件上,所以我的问题是,这在ES6中真的是不可能的,还是我缺少了什么?我已经知道这不是最佳实践,可以接受建议,但是即使对于不熟悉ES6的人来说,该想法也易于使用.

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? 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及更高版本旨在避免污染全局范围.您所关心的只是 JavaScript中许多邪恶的糟糕编码实践的解决方案.

ES6 and above has been designed to avoid polluting the global scope. Your concerns are just the solution to a lot of evil bad coding practices in JavaScript.

顺便说一句,您始终可以访问 window 对象并添加一个与您的类相同的属性:

BTW, you can always access window object and add a property called the same way as your class:

class Validator {}

window.Validator = Validator;

...因为类仍然是构造函数,并且被基于类的语法包裹着原型继承.

...because a class is still a constructor function and prototypal inheritance wrapped by a class-based syntax.

如果要在浏览器和NodeJS中分发库,则可能需要这样做:

If you're going to distribute your library both in browsers and NodeJS, you might want to do this:

class Validator {}

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

顺便说一句,如果您想以正确的方式做事,则可以使用通用模块定义来分发您的库.在通用模块定义(UMD)的官方GitHub存储库中了解更多信息.

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).

这篇关于在ES6中将类绑定到Global Scope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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