2018년 5월 29일 화요일

[JavaScript 예제] 044 계층을 가진 네임스페이스 정의하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>계층을 가진 네임스페이스 정의하기</title>
</head>
<body>
  <script>
  var namespace = function(ns) {
    // 네임스페이스를 '.'로 분할
    var elems = ns.split('.');
    var parent = window;

    // 이후 네임스페이스를 차례로 계층화하면서 등록
    for(var i=0, len=elems.length; i<len; i++) {
      parent[elems[i]] = parent[elems[i]] || {};
      parent = parent[elems[i]];
    }

    return parent;
  };

  // Myapp.Recipe.Samples 네임스페이스를 등록
  var ns = namespace('Myapp.Recipe.Samples');
  // 네임스페이스 예하에 클래스를 정의
  ns.MyClass = function() {};
  var c = new ns.MyClass();
  console.log(c instanceof Myapp.Recipe.Samples.MyClass); // true
  </script>
</body>
</html>



[JavaScript 예제] 043 클래스 이름 충돌 피하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>클래스 이름 충돌 피하기</title>
</head>
<body>
  <script>
  var Info = Info || {};  // Info가 비어 있는 경우에만 새로운 이름 공간을 작성

  Info.Person = function(name, birth) {
    this.name = name;
    this.birth = birth;
  };

  Info.Person.prototype.toString = function() {
    return this.name + ' _ _ ' + this.birth;
  }

  var p = new Info.Person('이정우', new Date(1981, 5, 16));
  console.log(p.toString());
  </script>
</body>
</html>


[JavaScript 예제] 042 객체형 판정하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>객체형 판정하기</title>
</head>
<body>
  <script>
  var Person = function() {};               // 함수 선언
  var BusinessPerson = function() {};       // 함수 선언
  BusinessPerson.prototype = new Person();  // Person을 상속
  var bp = new BusinessPerson();            // BusinessPerson 객체 생성

  console.log(bp instanceof BusinessPerson);  // 결과 true
  console.log(bp instanceof Person);          // 결과 true
  console.log(bp instanceof Object);          // 결과 true
  </script>
</body>
</html>



2018년 5월 28일 월요일

[JavaScript 예제] 040 클래스 상속하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>클래스 상속하기</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  // 부모 클래스 Person
  var Person = function() {};
  Person.prototype = {
    eat : function() {console.log('우물우물');}
  };

  // Person 클래스를 상속한 BusinessPerson 클래스
  var BusinessPerson = function() {};
  BusinessPerson.prototype = new Person();

  BusinessPerson.prototype.work = function() { console.log('먹보');}

  var bp = new BusinessPerson();
  bp.eat();
  bp.work();
  </script>
</body>
</html>




[JavaScript 예제] 037 클래스 정의하기

JavaScript에서 클래스르르 정의하려면 함수를 이용한다.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>클래스 정의하기</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  var Animal = function(name) {
    this.name = name;
    this.toString = function() {
      return 'Animal:' + this.name;
    };
  };

  var ani = new Animal('바루');
  console.log(ani.name);
  console.log(ani.toString());  
  </script>
</body>
</html>


프로토타입 기반 객체 지향

  • JavaScript는 객체 지향 언어이지만 그 구문은 프로토타입이라는 개념을 바탕으로 하고, 그 특수성을 말할 때 대표적인 특징으로 예를 든다.
    • 일반적인 클래스 기반 객체 지향에 대하여 프로토타입 기반의 객체 지향이라고 한다
  • 무엇보다 프로토타입 자체는 조금도 특수한 것이 아니라 '제약이 느슨한 클래스' 같은 것으로 인식하면 된다.


주의

  • 이름은 대문자로 시작한다.
  • 프로퍼티는 'this.프로퍼티 이름' 으로 정의한다.
  • 메소드는 함수형 프로퍼티이다.
  • 반환값은 필요 없다.
    • 생성자에서 자동으로 this가 가리키는 객체를 돌려주기 때문에 반환값은 필요 없다.
    • 명시적으로 반환값을 돌려준 경우 그 값이 new 연산자의 값이 된다.
      • 이 경우 this에 대한 프로퍼티 설정 등은 무시되므로 주의


new 연산 없이 호출 경우

1
2
3
4
5
6
var Animal = function(name) {
  if(!(this instanceof Animal)) {
    return new Animal(name);
  }
  // 코드 구성
}


클래스에 메소드 추가하기

생성자함수.prototype.메소드명 = function(...) {...}

정적 멤버 추가하기

생성자함수.프로퍼티명 = 값
생성자함수.메소드명 = function(...) {...}




[JavaScript 예제] 033 함수를 인수로서 전달하기




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>함수를 인수로서 전달하기</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  function benchmark(proc) {
    var start = new Date();
    proc();
    var end = new Date();
    return end.getTime() - start.getTime();
  }

  console.log(
    benchmark(function() {
      var x = 15;
      for(var i=0; i<10000000; i++) {
        x *= i;
      }
    })
  );
  </script>
</body>
</html>



[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}입니다.', '햄스터', '롤리'));