프로그래밍/자바스크립트

Javascript - 객체 생성 과정 및 상속

가카리 2015. 1. 25. 19:49
반응형

1.   객체 생성 과정



2.   프로토타입 체인과 프로토타입 멤버 상속


Function 객체의 주요 멤버




06-01.html


<!DOCTYPE html>

<html lang="ko">

  <head>

    <meta charset="utf-8" />

    <title>06-01</title>

  </head>

  <body>

    <script type="text/javascript">

          // 프로토타입 체인과 프로토타입 멤버 상속

      

      // Car 생성자 함수의 프로토타입 객체는 new 연산자와 Object 생성자 함수 호출을 통해 생성된 객체이며,

      // 프로토타입 객체에 constuctor 프로퍼티는 자동으로 Car 생성자 함수를 참조합니다.

      var Car = function(){};

      Car.prototype = {

        startEngine : function(){

          document.writeln('시동을 겁니다...<br/>');

        },

        accelerate : function(){

          document.writeln('속도를 올립니다...<br/>');

        },

        decelerate : function(){

          document.writeln('속도를 줄입니다...<br/>');

        },

        stopEngine : function(){

          document.writeln('시동을 끕니다...<br/>');

        }

      };


      // K5 생성자 함수의 프로토타입 객체는 new 연산자와 Object 생성자 함수 호출을 통해 생성된 객체이며,

      // 프로토타입 객체에 constuctor 프로퍼티는 자동으로 K5 생성자 함수를 참조합니다.

      var K5 = function(){};


      // K5() 생성자 함수의 prototype 프로퍼티가 new 연산자와 Car() 생성자 함수 호출을 통해 생성된 객체를

      // 참조하면 Car() 생성자 함수의 프로토타입 멤버를 상속하게 됩니다.

      K5.prototype = new Car();

      // 프로토타입 객체가 Car() 생성자 함수를 통해 만들어졌기 때문에 constructor 프로퍼티는

      // Car() 생성자 함수를 참조하게 됩니다. 따라서 constructor 프로퍼티를 K5() 생성자 함수로 변경합니다.

      K5.prototype.constructor = K5;

      

      K5.prototype.startNavigation = function(){

        document.writeln('네비게이션 안내를 시작합니다...<br/>');

      };

      K5.prototype.stopNavigation = function(){

        document.writeln('네비게이션 안내를 종료합니다...<br/>');

      };

      

      var k5 = new K5();

      k5.startEngine();

      k5.startNavigation();

      k5.accelerate();

      k5.decelerate();

      k5.stopNavigation();

      k5.stopEngine();

      

      document.writeln('<br/>');

    </script>

  </body>

</html>


출력화면



3.   객체 멤버 상속




06-02.html


<!DOCTYPE html>

<html lang="ko">

  <head>

    <meta charset="utf-8" />

    <title>06-02</title>

  </head>

  <body>

    <script type="text/javascript">

      // 객체 멤버 상속을 위해 Function() 생성자의 메소드 apply() call() 사용해 구현하는  생성자 체이닝

      

      var Car = function(f){

        this.fuel = f;

        this.velocity = 0;

        this.isDriving = false;

      };

      

      Car.prototype = {

        startEngine : function(){

          this.isDriving = true;

          this.fuel -= 5;

          document.writeln('Car: 시동을 겁니다... (isDriving: ' + this.isDriving + ', fuel: ' + this.fuel + ')<br/>');

        },

        accelerate : function(){

          this.velocity += 5;

          this.fuel -= 5;

          document.writeln('Car: 속도를 올립니다++++ (velocity: ' + this.velocity + ', fuel: ' + this.fuel + ')<br/>');

        },

        decelerate : function(){

          this.velocity -= 5;

          this.fuel -= 1;

          document.writeln('Car: 속도를 줄입니다---- (velocity: ' + this.velocity + ', fuel: ' + this.fuel + ')<br/>');

        },

        stopEngine : function(){

          this.isDriving = false;

          this.fuel -= 5;

          document.writeln('Car: 시동을 끕니다... (isDriving: ' + this.isDriving + ', fuel: ' + this.fuel + ')<br/>');

        }

      };


      var K5 = function(f, m){

        // 객체 멤버 상속 매개변수 배열을 넘겨줌

        Car.apply(this, [f]); // 또는 Car.call(this, f);

        this.model = m;

      };


      K5.prototype = new Car();

      K5.prototype.constructor = K5;//K5 반드시 생성자를 지정해야됨

      delete K5.prototype.fuel;//Car 생성자 함수를 호출하면 3 변수는 알아서 처리해서 정보는 K5 prototype 있을 필요가 없음

      delete K5.prototype.velocity;

      delete K5.prototype.isDriving;

      

      //오버라이딩

      K5.prototype.accelerate = function(){

        this.velocity += 10;

        this.fuel -= 5;

        document.writeln('K5 ' + this.model + ': 속도를 올립니다++++ (velocity: ' + this.velocity + ', fuel: ' + this.fuel + ')<br/>')

      };

      

      K5.prototype.decelerate = function(){

        this.velocity -= 10;

        this.fuel -= 1;

        document.writeln('K5 ' + this.model + ': 속도를 줄입니다---- (velocity: ' + this.velocity + ', fuel: ' + this.fuel + ')<br/>');

      };

      

      K5.prototype.startNavigation = function(){

        document.writeln('K5 ' + this.model + ': 네비게이션 안내를 시작합니다...<br/>');

      };

      

      K5.prototype.stopNavigation = function(){

        document.writeln('K5 ' + this.model + ': 네비게이션 안내를 종료합니다...<br/>');

      };

      

      var k5 = new K5(1000, '2013년형');

      document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      k5.startEngine();

      document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      k5.startNavigation();

      for (var i = 0; i < 5; i++)

        k5.accelerate();

        document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      for (var i = 0; i < 5; i++)

        k5.decelerate();

        document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      k5.stopNavigation();

      document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      k5.stopEngine();

      document.writeln('>>> k5.fuel: ' + k5.fuel + '<br/>');

      

      document.writeln('<br/>');

    </script>

  </body>

</html>


출력화면




4.   객체의 타입 검사

                           


06-03.html


<!DOCTYPE html>

<html lang="ko">

  <head>

    <meta charset="utf-8" />

    <title>06-03</title>

  </head>

  <body>

    <script type="text/javascript">

      // typeof, instanceof, constructor 이용한 객체의 타입 검사

      

      function checkType(obj) {

        // 먼저 null 경우 문자열 'null' 반환합니다.

        if (obj == null)

          return 'null';

        

        // 제일 먼저 typeof 연산자를 이용해 문자열을 취합니다.

        var type = typeof obj;

        

        // typeof 반환 값이 'object' 아닐 경우 type 값을 반환합니다.

        if (type != 'object')

          return type;

        

        // obj.toString() 결과를 str 변수에 저장합니다.

        //call 메소드에 obj this 지정함

        var str = Object.prototype.toString.call(obj);

        

        // 생성자 이름을 추출합니다.

        var constructor = str.substring(8, str.length - 1);//시작 인덱스, 종료인덱스

        

        // 'Object' 경우엔 constructor 프로퍼티까지 조사할 필요가 있습니다.   

        if (constructor != 'Object')

          return constructor;

        

        // 실제 Object 타입일 경우 constructor 값을 반환합니다.

        if (obj.constructor == Object)

          return constructor

        

        // 사용자 정의 객체의 생성자 함수의 프로토타입 객체에 정의해 놓은 constructorname

        // 프로퍼티가  있으면 constructorname 반환합니다.

        if ('constructorname' in obj.constructor.prototype)

            return obj.constructor.prototype.constructorname;

        

        return '객체의 타입을 없습니다.';     

      }

      

      var Parent = function() {};

      Parent.prototype.constructorname = 'Parent';

      

      var Child = function() {};

      Child.prototype = new Parent();

      Child.prototype.constructor = Child;

      Child.prototype.constructorname = 'Child';//꼭해야됨

      

      var child = new Child();

      

      document.writeln('typeof Parent: ' + typeof Parent + ' <br/>');

      document.writeln('typeof Child: ' + typeof Child + ' <br/>');

      document.writeln('typeof child: ' + typeof child + ' <br/>');

      document.writeln('child instanceof Object: ' + (child instanceof Object) + ' <br/>');

      document.writeln('child instanceof Parent: ' + (child instanceof Parent) + ' <br/>');

      document.writeln('child instanceof Child: ' + (child instanceof Child) + ' <br/>');

      document.writeln('child.constructor === Object: ' + (child.constructor === Object) + ' <br/>');

      document.writeln('child.constructor === Parent: ' + (child.constructor === Parent) + ' <br/>');

      document.writeln('child.constructor === Child: ' + (child.constructor === Child) + ' <br/>');

      document.writeln('<br/>');

      

      document.writeln('checkType(child): ' + checkType(child) + ' <br/>');

      

    </script>

  </body>

</html>



출력화면


반응형