코딩하는 문과생

자바스크립트/ 06. 프로토타입 링크 본문

웹 프로그래밍/Javascript

자바스크립트/ 06. 프로토타입 링크

코딩하는 문과생 2018. 11. 4. 13:28

06. 프로토타입 링크


자바스크립트에서 일반적으로 객체지향 프로그래밍에서 쓰이는 상속 이라는 개념을 이용하기 위해

프로토타입 개념을 씁니다.


1)classical 타입


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
  function Car(m){
    this.model = m || "Benz";
  }
  Car.prototype.getModel = function(){
    return this.model;
  }
 
  function childCar(model){this.model = model}
  childCar.prototype = new Car(); //childCar 객체가 Car 객체를 상속받는다.
 
  var myCar = new childCar("BMW");
  document.write(myCar.getModel());//childCar에 해당하는 getModel메서드가 존재하지 않는다. 
    //따라서 부모 객체의 메서드를 찾는다.
</script>
 
cs


<실행결과>




2)prototypical 타입


- 선호되는 방식입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
    var parentCar = {
        model  : "BMW",
        speed : 100,
        color : "Black",
        speedUp : function(){
            this.speed += 10;
            return this.speed;
        },
        speedDown : function(){
            this.speed -=10;
            return this.speed;
        }
    };
    var first = Object.create(parentCar);//first 객체 생성
        //Object.create()를 이용해서 상위 생성자의 속성과 메서드를 상속받았다.
    first.battery = false//자식객체에 속성값을 지정
    document.write(first.battery);
</script>
 
cs


<실행결과>