jQuery for Pure Javascript (use export Function ES6)

Asked

Viewed 120 times

1

This script capitalizes the first letter of each word, except for a few words that are part of the matrices in the variables wordContainAt, wordsToIgnore, wordUpperCase.

I’m having trouble refactoring the code created on jQuery for JavaScript Puro. I intend to use módulos de exportação ES6.

I know that export has nothing to do with function, but in this context, I don’t think I understand very well the concept of a função anônima, or arrow function, because I can’t get the object thiswithin the scope of the function, as in jQuery.

Can someone help me ?

jQuery

$(window).on('load', function() {
    $.fn.capitalize = function() {
        // words to ignore
        let wordContainAt = '@',
            wordsToIgnore = ['to', 'and', 'the', 'it', 'or', 'that', 'this'],
            wordUpperCase = ['S.A', 'SMS', 'USA'],
            minLength = 2;

        function getWords(str) {
            if (str == undefined) {
                str = 'abc def';
            } else {
                str = str;
            }
            return str.match(/\S+\s*/g);
        }
        this.each(function() {
            let words = getWords(this.value);
            console.log(words);
            $.each(words, function(i, word) {
                // only continues if the word is not in the ignore list or contains at '@'
                if (word.indexOf(wordContainAt) != -1) {
                    words[i] = words[i].toLowerCase();
                } else if (wordUpperCase.indexOf($.trim(word).toUpperCase()) != -1) {
                    words[i] = words[i].toUpperCase();
                } else if (wordsToIgnore.indexOf($.trim(word)) == -1 && $.trim(word).length > minLength) {
                    words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
                } else {
                    words[i] = words[i].toLowerCase();
                }
            });
            if (this.value != '') {
                this.value = words.join('');
            }
        });
    };

    // field onblur with class .lower
    $(document).on('blur', '.lower', function() {
        $(this).capitalize();
    }).capitalize();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="lower" />

Javascript example

const capitalizeTheWord = () => {
    constole.log(this) // undefined

    const inputWordCapitalize = document.querySelector('input.lower');
    inputWordCapitalize.addEventListener('blur', (e) => {
        // capitalizeTheWord...
    });
};

export default capitalizeTheWord();

1 answer

2


First of all, it is worth making clear that in Javascript, an anonymous function is not necessarily a Arrow Function. Anonymous functions are simply those not named.

See, first, an example of a named function:

function doStuff() { /* ... */ }
//       ↑↑↑↑↑↑↑
//    Nome da função

And some examples of anonymous functions:

const doStuff1 = function() {};

const doStuff2 = () => {};

Note that the function itself has no name. As an expression returns, it will be assigned to the variables doStuff1 and doStuff2, that will store the - anonymous function. Note that you can still invoke them normally, since they are functions.

Anonymous functions are usually used as callbacks. If you will create a function that you will call yourself, it is always preferable to declare it using a name.


Now in the context of Arrow functions, should, first of all, consult the documentation. In summary, the this is undefined because all Arrow Function does not create a value this for its own purpose. The this is inherited from the parent scope.

Thus, as the parent scope of his Arrow Function is the very module, this will be undefined.

See an example illustrating the behavior of Arrow Function of not creating a value this for his own purpose, inheriting his father’s scope:

class Class {
  constructor(foo) {
    this.foo = foo;
  }
  
  doStuff() {
    console.log(this.foo);
    
    // Note que estamos retornando uma arrow function:
    return () => {
      console.log(this.foo);
    };
  }
}

const instance = new Class('Given String');
const returnedFn = instance.doStuff(); // Irá imprimir no console: "Given String"
returnedFn(); // Irá imprimir no console: "Given String"

By way of comparison, see the same example, but changing the Arrow Function by a conventional anonymous function:

class Class {
  constructor(foo) {
    this.foo = foo;
  }
  
  doStuff() {
    console.log(this.foo);
    
    // Note que estamos retornando uma função anônima convencional:
    return function() {
      console.log(this); // `this` é undefined. Se tentar acessar `foo`, um erro será lançado.
    };
  }
}

const instance = new Class('Given String');
const returnedFn = instance.doStuff(); // Irá imprimir no console: "Given String"
returnedFn(); // Irá imprimir no console: undefined


Having said that, I don’t even know why you want to access the this within the function you are already calling when exporting it. Incidentally, you are neither exporting the function, but rather your return, which seems to me to be undefined, because there is no return explicit.

To learn more:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.