首页 > 解决方案 > 如何在javascript中的新型匿名函数中访问此关键字

问题描述

考虑一个非常简单的 HTML 片段和一些稍微不同的方法,将事件处理程序分配给 HTMLSELECT元素。问题在于使用匿名函数的形式( e )=>{ alert( this.value ) }

<select name='radius'>
    <option>1
    <option>2
    <option>3
    <option>4
    <option>5
    <option>10
</select>



<script>
    /*
        this works fine, as you'd expect
    */
    const changehandler=function(e){
        alert( this.value + ' '+e.target )
    }
    document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', changehandler );


    /*
        this works fine using `this` within the event handler when using the more traditional
        anonymous function
    */
    document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', function(e){
        alert( this.value )
    });


    /*
        this does not work as expected. `this` does not refer to the HTML element in this
        case - it now refers to `[object Window]`
    */
    document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', e=>{
        alert( this.value )
    });
</script>

我想我也许可以到bindHTML 元素,像这样:

let select=document.querySelector( 'select[name="radius"]' );
    select.addEventListener( 'change', e=>{ alert( this ) }.bind( select ) );

然而,这会导致错误Uncaught SyntaxError: missing ) after argument list

所以,问题是我能否this以某种方式访问​​这些新样式匿名函数中的关键字,并让它引用分配事件处理程序的 HTML 元素?有什么我忽略的小技巧吗?

标签: javascripthtml

解决方案


箭头函数表达式是正则函数表达式的语法紧凑替代方案,尽管它没有绑定到 this、arguments、super 或 new.target 关键字

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

当您想保留父作用域时,箭头函数很有用;如果您需要该功能拥有自己的功能this,请使用“传统”function() {...}结构。


推荐阅读