Not only can you provide default values when using ES6 parameter object destructuring, but you can also require the presence of certain properties.
function ajax({ type = "get", url = requiredParameter("url"), data = {}, success = requiredParameter("success"), error = () => {}, isAsync = true } = {}) { console.log(JSON.stringify({ type, url, data, success, error, isAsync }, null, 2)); } function requiredParameter(name){ console.log(`parameter missing: "${name}"`); } try{ ajax({url: ‘http://api.com‘, data: {name: ‘Zhentian‘}, success: false}) }catch(e){ console.log(JSON.stringify(e)) }
Now, success and url are rueqired, if we don‘t passin success, then it will show:
//"parameter missing: \"success\""
时间: 2024-10-11 00:48:45