본문 바로가기

개발/javascript&jquery

복잡한 인자 관리하기

반응형

복잡한 인자를 관리할때 

1. 객체로 사용하기

function createCar(name, brand, color, type) {
	return {
    	name, 
        brand,
        color,
        type
    }
}


function createCar({name, brand, color, type}) {
	return {
    	name, 
        brand,
        color,
        type
    }
}

첫번째 인자는 중요하고 나머지는 옵션이다는걸 명시적으로 보여줌 
function createCar(name, { brand, color, type}) {
	return {
    	name, 
        brand,
        color,
        type
    }
}

 

 

2. 명시적으로 함수를 사용하는 다른 개발자에게 에러를 만들어 줘서 인자를 안전하게 관리할 수 있다.

function createCar({name, brand, color, type}) {
	if(!name) {
    	throw new Error('name is a required')
    }
    if(!brand) {
    	throw new Error('brand is a required')
    }
}

createCar({name: 'CAR', type: 'SUV' });

 

 

3. default value / default parameter 

function createCar({name = '', brand ='', color = '', type = false} = {}) {
}

createCar({name: 'CAR', type: 'SUV' });
//name이 필수인경우
//default paramter로 할당된 함수가 실행됨 
const required(name) => {
	throw new Error('require' + name);
}
function createCar({name = required('name'), brand ='', color = '', type = false} = {}) {
}

createCar({ type: 'SUV' });

 

 

 

반응형