Cuando hago una función, verifico que los parámetros requeridos estén completos como se ve a continuación.
Pregunta
Realmente no es una buena manera, ya que todo lo que hace es asignar un valor predeterminado a un parámetro faltante. Prefiero que la ejecución se detenga y me diga a qué función le falta un parámetro. ¿Cómo se hace eso, si es posible?
func({ system: "test1", type: "test2", summary: "test3", description: "test4", }); function func (c) { c = c || {}; c.system = c.system || "Missing system"; c.type = c.type || 'Missing type'; c.summary = c.summary || 'Missing summary'; c.description = c.description || 'Missing description'; console.log(c); console.log(c.system); console.log(c.type); console.log(c.summary); console.log(c.description); };Lanzar un error si no encuentra el valor.
if(!c.system) throw new Error("Missing system"); // This would fail if c.system is falsy // In this case can be used: if(!c.hasOwnProperty("system")) throw new Error("Missing system")Puede crear una función para verificar esto.
function Check(objt, key, messageError){ if(!objt.hasOwnProperty(key)) throw new Error(messageError) } Check(c, "system", "Missing system");