任何人都可以向我解释这段代码的行为吗?
var arguments = 42;
var arr = () => arguments;
arr(); // 42
function foo() {
var f = (i) => arguments[0] + i; // foo's implicit arguments binding
return f(2);
}
foo(1); // 3
我知道什么是隐式参数绑定(bind)。
我不明白的是
foo(1)
是如何返回 3 的?return f(2)
有什么作用?它调用了哪个函数?
PS:我在关注this Mozilla 文档。
最佳答案
箭头函数不绑定(bind) arguments
所以当你在 f
中使用 arguments[0]
你访问的是 foo
的参数(即 1
)。由于您已将 2 作为 i
传递,您将得到 1 + 2
例如,如果您使用箭头函数尝试访问函数调用之外的参数,您应该得到一个ReferenceError
const f = i => console.log(arguments[0])
try {
f()
console.assert(false, 'should not get here')
} catch (e) {
console.assert(e instanceof ReferenceError,
'should get reference error on trying to access arguments')
console.log(e.message)
}
关于javascript - JavaScript 中没有参数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032751/