Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel transform this by _this

I have a bootstrap modification for a tooltip. and process my js with webpack/babel

A simplification of my code could be:

    $('[data-toggle="tooltip"]').tooltip({
        title: () => {
            return $(this).children('.tooltip-html-content').html();
        }
    });

This should be the element, bootstrap will call this function with:

   getTitle: function () {
      var title
        , $e = this.$element
        , o = this.options

      title = $e.attr('data-original-title')
        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

      return title
    }

The important line is:

 o.title.call($e[0])

Where $e[0] is the tooltip dom element.

Well, when I process this with babel the result change this by _this a before he assign _this to a value that he consider is the real this.

The question: Can I avoid this conversion in babel for this specific function?

=====

Final solution based in the response:

   getTitle: function getTitle() {
like image 601
Raúl Martín Avatar asked Jul 15 '16 17:07

Raúl Martín


1 Answers

You've used an arrow function, which by definition closes over the this where it's created.

If you don't want that behavior, don't use an arrow function:

$('[data-toggle="tooltip"]').tooltip({
    title: function() {
    // ----^^^^^^^^^^
        return $(this).children('.tooltip-html-content').html();
    }
});

Re your edit:

I want to use the arrow function. I prefer do a babel exclusion than an eslint exclusion.

You can't, not with that getTitle, since the only way it gives you access to the element is by setting this. Arrow functions by their nature have a fixed this (by not having one at all; they close over the one in the execution context where they were created, which is fixed). You cannot use an arrow function for any function where you want this determined by the caller, such as in this case.

Your choices are either to modify Bootstrap, or use a normal function. The latter seems the more reasonable thing to do.

like image 147
T.J. Crowder Avatar answered Sep 27 '22 19:09

T.J. Crowder