2018년 5월 28일 월요일

[JavaScript 예제] 028 함수 정의하기


함수 정의하기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// function 명령
function getSquareArea(width, height) {
  return width * height;
}

// Function 생성자
var getSquareArea = new Function(
  'width', 'height', 'return width * height;');

// 함수 리터럴
var getSquareArea = 
  function(width, height) { return width * height; };

console.log(getSquareArea(2, 3));
Function 생성자는 사용을 하지 않기를....


인수의 기본값 설정하기

1
2
3
4
5
6
7
8
9
function getSquareArea(o_width, o_height) {
  if( o_width === undefined ) { o_width = 1; }
  if( o_height=== undefined ) { o_height= 1; }
  return o_width * o_height;
}

colsole.log(getSquareArea(10, 5));
colsole.log(getSquareArea(10));
colsole.log(getSquareArea());



필수 인수 확인하기

1
2
3
if(width === undefined) {
  throw { name: 'ArgsMissing', message: '폭이 지정되지 않았습니다.' };
}



값만 전달하는 인수와 명명된 인수

1
showPanel('content.html', 200, 300, true, true, false);

1
2
3
4
5
6
7
8
showPanel({
  Path: 'content.html',  // 패널로 표시하는 내용
  height: 200,           // 높이
  width: 300,            // 폭
  resizable: true,       // 리사이즈 가능여부
  draggable: true,       // 드래그 가능여부
  modeless: false        // 모달리스 패널여부
});


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function showPanel(args) {
  if(args.path === undefined) {
    throw { name: 'ArgsMissing', message: 'path는 필수임.' };
  }
  if(args.height === undefined) { args.height = 200; }
  if(args.width === undefined) { args.width = 300; }
  if(args.resizable === undefined) { args.resizable = true; }
  if(args.draggable === undefined) { args.draggable = true; }
  if(args.modeless === undefined) { args.modeless = false; }
  // ..... 구현부분
}


가변 길이 인수를 갖는 함수정의
- 기본예
1
2
3
4
5
6
7
8
9
function max(v_args) {
  var result = Number.NEGATIVE_INFINITY;
  for(var i=0, len=arguments.length; i<len; i++) {
    if(result < arguments[i]) {
      result = arguments[i];
    }
  }
  return result;
}

- 고정인수와 가변 인수가 함께 있는 예

1
2
3
4
5
6
7
8
9
function sprintf(format) {
  for(var i=1, len=arguments.length; i<len; i++) {
    var pattern = new RegExp('\\{' + (i-1) + '\\}', 'g');
    format = format.replace(pattern, arguments[i]);
  }
  return format;
}

console.log(sprintf('{0}를 키우는데 이름은 {1}입니다.', '햄스터', '롤리'));


댓글 없음:

댓글 쓰기