简体   繁体   English

Babel通过_this转换它

[英]Babel transform this by _this

I have a bootstrap modification for a tooltip. 我有一个工具提示的bootstrap修改。 and process my js with webpack/babel 并使用webpack / babel处理我的js

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: 这应该是元素,bootstrap将调用此函数:

   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. 其中$ e [0]是工具提示dom元素。

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. 好吧,当我用babel处理这个时,结果会改变this _this a之前他将_this分配给他认为真实的值。

The question: Can I avoid this conversion in babel for this specific function? 问题:我可以在babel中避免这种特定功能的转换吗?

===== =====

Final solution based in the response: 基于响应的最终解决方案:

   getTitle: function getTitle() {

You've used an arrow function, which by definition closes over the this where it's created. 你已经使用了一个箭头的功能,它通过定义封闭在this地方它的创建。

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. 我宁愿做一个排除babel而不是排除eslint。

You can't , not with that getTitle , since the only way it gives you access to the element is by setting this . 你不能 ,不能使用getTitle ,因为它允许你访问元素的唯一方法是设置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). 通过它们的性质箭头功能已固定的this (通过不具有一个在所有;它们关闭在所述一个在它们被创建的执行上下文,这是固定的)。 You cannot use an arrow function for any function where you want this determined by the caller, such as in this case. 您不能使用箭头功能,你想要的任何功能, this被调用者确定,如在这种情况下。

Your choices are either to modify Bootstrap, or use a normal function. 您可以选择修改Bootstrap,也可以使用普通功能。 The latter seems the more reasonable thing to do. 后者似乎更合理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM