分解函数参数中的默认值导致ReferenceError

I needed to set a default value for db in my CRUD functions for testing purposes and encountered a strange behaviour, I could not figure out yet. Consider the following code:

import { db } from './firebase'

function getUsers({ db = db }) {
  try {
    return db
    ...

Now, when I use the function in my tests, there is no problem, since I invoke the function in my test file with a test db. But the real app should be able to fall back on the default value and call the function without any params. But here, I encounter the error: ReferenceError: can't access lexical declaration 'db' before initialization. I have no idea why this happens.

我通过重命名参数找到了解决方法。但是,我仍然很想知道这里发生了什么。有人有主意吗?

解决方法:

import * as firebase from './firebase'

function getUsers({ db = firebase.db }) {
  try {
    return db
评论
  • oautem
    oautem 回复

    That's the way scope works in function declaration parameter lists. The scope of the default argument value context includes the parameter list itself (well, the ones already declared). Thus the db parameter shadows the relatively global symbol from the import.

    您也可以通过更改参数名称来解决此问题:

    function getUsers({database = db})
    

    范围以这种方式工作,因此可以在表达式的参数列表中的较早参数中使用参数,以便稍后在列表中使用参数:

    function something(a, b = a + 1)
    

    Calling that function like something(0) would set b to 1.