ES6中命名的对象参数 - 如何检查它们?

时间:2017-08-09 09:12:04

标签: javascript ecmascript-6

我有一些ES6代码,我传递一个已定义的选项对象的一些命名参数,如此...

let metaData = GTLRDrive_File()
    metaData.name = "xyz"
    metaData.mimeType = "application/vnd.google-apps.folder"
    let querys = GTLRDriveQuery_FilesCreate.query(withObject: metaData, uploadParameters: nil)

    querys.fields = "id"

    //service.executeQuery(querys, delegate: self, didFinish: nil)

    self.service.executeQuery(querys) { (ticket:GTLRServiceTicket, object:Any?, error:Error?) in
        // Put your completion code here
    }

这是一个人为的案例,以下调用将正常工作......

    configureMapManager({ mapLocation, configuredWithDataCallback, locationHasChanged })
{
    if (mapLocation) console.log(mapLocation)
}

但这会爆发......

configureMapManager({ mapLocation: "BS1 3TQ" })
configureMapManager({})

...因为我无法检查传入的对象是否已定义(这不是因为我调用了没有任何参数的方法)。我怎么能这样做而不必像这样重写(这很糟糕,因为你失去了对象中允许参数的可见性)......

configureMapManager()

1 个答案:

答案 0 :(得分:4)

使用默认参数:

function configureMapManager({ mapLocation } = {})
{
  console.log(mapLocation);
}

在没有任何参数的情况下调用函数时,mapLocation将是未定义的:

configureMapManager(); // prints: undefined
configureMapManager({ mapLocation: 'data' }); // prints: data