JonnySerra JonnySerra - 1 year ago 91
jQuery Question

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

anywhere, it'll run the associated function in the
and add a method to the

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

Answer Source

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