javascript - 如何在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>
我想我也许可以到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、arguments、super 或 new.target 关键字。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
当您想保留父作用域时,箭头函数很有用;如果您需要该功能拥有自己的功能this
,请使用“传统”function() {...}
结构。
推荐阅读
- xamarin - 如何将谷歌支付集成到我的安卓应用中进行支付
- forms - 表单操作将我转发到显示 JSON (JavaScript) 的另一个页面
- php - 仅在 WooCommerce 中替换管理单订单页面上的标题文本
- javascript - 输入元素如何检查字符串是否匹配模式属性中指定的正则表达式?
- julia - 我可以将关键字 args 传递给 julia 中的 do-blocks 吗?
- javascript - ENOENT:运行 fs.readFile 时没有这样的文件或目录
- javascript - jQuery inArray 返回 false
- c# - 如何在验证错误时禁用按钮
- java - 如何以逻辑方式附加文本等
- python - 使用 while 循环递增数组中的值,直到所有值 => 100