如何在箭头功能内访问Argument对象 [英] How to access Argument object inside arrow function
问题描述
listOfArg
函数中的自变量Object引用带有箭头功能的父arguments
.而且,如果没有箭头功能,this
键的引用将发生更改,并且listOfArg
函数将无法通过this
更改进行访问.
The arguments Object inside listOfArg
function refers to parent arguments
with arrow function. And without arrow function this
key reference would change and listOfArg
function will no longer accessible through this
change.
componentDidMount(){
document.addEventListener('scroll', this.onScrollEvent);
}
listOfArg = () => {
console.log(arguments)
}
onScrollEvent = (e) => {
this.listOfArg("1", "2", "3", "4")
}
推荐答案
来自 MDN文档
箭头函数没有自己的this;使用封闭执行上下文的this值.
An arrow function does not have its own this; the this value of the enclosing execution context is used.
如果您使用
listOfArg = () => {
console.log(arguments)
}
onScrollEvent
中的
this
将引用组件this
,并且您将获得传递给该组件的参数,因为箭头函数将使用封闭的执行上下文,即React组件.
this
inside onScrollEvent
would refer to the component this
and you would get arguments passed to the component because arrow function would use enclosing execution context which is the React Component.
现在,如果您不使用箭头功能:
Now, if you do not use arrow function:
listOfArg() {
console.log(arguments)
}
在这里,listOfArg
将有其自己的this
,并会打印调用它的参数:["1", "2", ...]
,这是预期的.
Here, listOfArg
will have its own this
and would print arguments it was called with: ["1", "2", ...]
which is expected.
这篇关于如何在箭头功能内访问Argument对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!