如何在javascript中的新样式匿名函数中访问此关键字



考虑一个非常简单的 HTML 片段和一些稍微不同的将事件处理程序分配给 HTML SELECT 元素的方法。问题在于使用表单的匿名函数( 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>

我想我也许可以bind HTML 元素,如下所示:

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

但是,这会导致错误Uncaught SyntaxError: missing ) after argument list

因此,问题是我是否可以以某种方式访问这些新样式匿名函数中的this关键字,并使其引用事件处理程序分配到的HTML元素?是不是我忽略了一些小技巧?

箭头函数表达式

是正则函数表达式的语法紧凑替代项,尽管它没有自己的绑定到 this、参数、super 或 new.target 关键字

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

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

最新更新