Bind classes to Global Scope in ES6

余生长醉 提交于 2021-01-06 18:50:29

问题


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.

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;
})

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.


回答1:


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.

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.

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;

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



来源:https://stackoverflow.com/questions/38796519/bind-classes-to-global-scope-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!