[JavaScript] Chapter 5. 대규모 개발에서도 통용되는 작성법 익히기 - 객체지향 구문

Coffee Time☕·2020년 7월 23일

javascript

목록 보기
5/8

5.1 JavaScript 의 객체지향 특징

  • Class 없음, prototype 만 존재한다. 프로토타입이라는 것은 어떤 객체의 원본이 되는 객체인데, 이는 js 의 프로토타입 베이스의 객체지향이라고 한다.
  • 클래스 based 객체 지향과 다른 점은 prototyped 베이스 객체 지향이 속박이 좀 더 약하다는 점이다.

Class 정의(prototype을 편의상 class라 함)

  • var Member =function(){ } ;
  • var mem= new Member(); //Member class에 대한 instance 를 생성함

프로퍼티와 메소드

  • this 키워드를 이용한다. (this.name='값';)
  • 생성자 초기화 예시
    var Member(firstName,lastName){
    	this.firstName=firstName;
       this.lastName=lastName;
       this.getName()=function(){
       	return this.lastName+' '+this.firstName;
       }
    };

5.2 생성자의 문제점과 프로토타입

  • 메소드는 프로토 타입으로 선언한다.
    객체를 인스턴스화 했을 경우, 인스턴스는 베이스가 ㄱ되는 객체에 속하는 prototype 객체에서 암묵적인 참조를 갖게 된다.
    var Member =function (firstName,lastName){
    	this.firstName=firstName;
       this.lastName=lastName;
    }
    Member.prototype.getName=function(){
    	return this.lastName+''+this.firstName;
    }
    
    var mem=new Member('John','Kim');
    console.log(mem.getName());
  • 프로토타입 객체를 사용한 메소드 정의의 두가지 이점
  1. 메모리의 사용량을 절감할 수 있다.
    JavaScript에서는 인스턴스 측에 요구된 멤버가 존재하는지 하지 않는지 확인하며, 않는 경우, 암묵적인 참조만을 통해 프로토타입 객체를 검색한다.
  2. 멤버의 추가나 변경을 인스턴스가 실시간으로 인식할 수 있다.
    프로토타입 객체로의 변경을 인스턴스 측에서 동적으로 인식할 수 있다.
  • 프로토타입 객체의 불가사의 - 프로퍼티의 설정
    var Member= function (){};
    Member.prototype.sex='남자';
    var mem1=new Member();
    var mem2=new Member();
    console.log(mem1.sex+''+mem2.sex); //결과: 남자 남자
    mem2.sex='여자';
    console.log(mem1.sex+''+mem2.sex); //결과: 남자 여자
  • 프로토타입 객체의 불가사의2- 프로퍼티의 삭제
delete mem1.sex;
delete mem2.sex; 
console.log(mem1.sex+''+mem2.sex); //결과: 남자 남자
  • 객체 리터럴로 프로타입 정의하기
    var Member=function(firstName,lastName){
    	this.firstName=firstName;
       this.lastName=lastName;
    };
    Member.prototype={
    	getName:funtion(){
       	return this.lastName+''+this.firstName;
       }
       toString:function(){
       	return this.lastName+this.firstName;
        }
  • 정적 프로퍼티는 기본적으로 읽기 전용의 용도로 사용한다.
  • 정적 메소드 안에서는 this 키워드를 사용할 수 없다.

5.3 객체의 계승- 프로토타입 체인

프로토타입 체인의 기초

  • 계승 : 상속과 유사한 개념이 아닌가 싶다. base가 되는 객체의 기능을 계승하여 새로운 클래스를 정의하는 기능을 말한다.
  • 프로토타입 체인
    var Animal=function(){};
    Animal.prototype={
    	walk: function(){
      	console.log('종종');
          }
      };
      
     var Dog=function(){
     	 Animal.call(this);
      };
      Dog.prototype=new Animal();
      Dog.prototype.bark=function(){
      	console.log('멍');
       }
       var d =new Dog();
       d.walk();
       d.bark();
  • 계승 관계는 동적으로 변경 가능
    var Animal=function(){};
    Animal.prototype={
    	walk: function(){
       	console.log('종종');
           }
       };
       
       var SuperAnimal=function(){};
       SuperAnimal.prototype={
       	walk:function(){
           	console.log(' 다다');
           }
        };
        var Dog=function(){};
        Dog.prototype=new Animal()l
        var d1=new Dog();
        d1.walk();
  • 객체의 타입 판정하기
    1.constructor 프로퍼티
    var Animal=function(){};
    var Hamster=function(){};
    Hamster.prototype=new Animal();
    var a=new Animal();
    var h=new Hmaster();
    console.log(a.constructor===Animal);//true
    console.log(h.construnctor===Animal);//true
    console.log(h.constructor===Hamster);//false
    2.instanceof 연산자
    console.log(Hamster.prototype.isPrototypeOf(h));
    console.log(Animal.prototype.isPrototypeOf(h));
    3.isPrototypeOf 메소드
    4.in 연산자
    var obj={hoge:function(){}, foo:function(){}};
    console.log('hoge' in obj);//true
    console.log('piyo' in obj);//false

5.4 본격적인 개발에 대비하기

private 멤버 정의하기

  • JavaScript에서는 private 멤버를 정의하기 위한 구문은 없으나 클로저를 이용함으로써 유사적으로 private 멤버를 정의할 수 있다. 먼저 다음 규칙을 기억해야한다.
  1. private 멤버는 생성자 함수에서 정의한다.

  2. privileged 메소드를 정의해 private 멤버에 액세스하기.

    function Triangle(){
    	//private property
    	var _base; 
       var _height;
       //private 메소드 정의
       var _checkArgs=function(base){
       	return (typeof val==='number'&&val>0);
        }
        //private 멤버에 엑세스하기 위한 메소드 정의
        this.setBase=function(base){
        	if(_checkArgs(base){base= _base;}
          }
         this.getBase=function(){return _base;}
         this.setHeight=function(height){
         	if(_checkArgs)){_height=height;}
          }
          this.getHeight=function(){return _height;}
      }

    Object.defineProperty 메소드에 의한 액세서 메소드 구현

    function Triangle(){
    	var _base;
       var _height;
       
       Object.defineProperty(
       	this,
           'base',
           {
           	get:function(){
               	return base;};
               set: function(base){
               	if(typeof base==number && base>0))
                   _base=base;
                   }
                };
            }
         }
      }
               

네임스페이스/ 패키지 작성하기

  • var Wings=Wings||{}; //wing 네임스페이스를 정의한 것임
    Wings.Member=function(firstName,lastName){
    	this.firstName=firstName;
       this.LastName=lastName;}; 
    Wings.Member.prototype={
    	getName:function(){
       	return this.lasName+''+this.firstName;
       }
    };
  • 계층을 지닌 네임스페이스 정의하기
    function namespace(ns){
    	var anems=ns.split('.');
       var parent =window;
       
       for( var i=0,len=names.length;i<len;i++){
       	parent[names[i]]=parent[names[i]]||{};
           parent=parent[names[i]];
           }
           return parent;
       }

5.5 ES2015 객체지향 구문

클래스 정의하기

class Member{
	constructor(firstName, lastName){
   	this.firstName=firstName;
       this.lastName=lastNamel
    }
    getName(){
    	return firstName;
     }
     
   }
   let m =new Member('kimmm','kim');
   
   get firstName(){
   	return this._firstName;
     }
     static getTriangle (base,height){
     	return base*height/2;
      }
 }

객체 리터럴의 개선

  • 메소드 정의
    let member={
    	name:'아무개',
       birth:new Date(1980,5,5,);
       to String(){
       	return this.name;
        }
     };
  • 변수를 동일 명칭의 프로퍼티에 할당하기
    let name='아무무';
    let birth=new Date(1990,10,20);
    let member={name,birth};
    //memeber 출력시 {name:"아무무", birth: October 20 1990 00:00:00

모듈

  • ES2015 부터 비로소 모듈이 지원이 되기 시작했다.
    다음과 같이 정의한다.

    import {Member, Area} from './lib/Util';
    var m =new Member('무무','아');
    console.log(m.getName());
  • default 의 export 가져오기

    export default class{
    	static getTriangle(base,height){
      	return base*height/2;
          }
     }
    

반복자(Iterator)

  • iterator_array.js
    	```
    	let data_Ary=['o','t','t2'];
    	let itr=data_ary[Symbol.iterator]();
    	let d;
    	while(d=itr.next()){
    		if (d.done) {break;}
      console.log(d.done);
      console.log(d.value);
    		}
    	 ```

발생자(Generator)

  • 열거 가능한 객체는 generator을 이용해서 더 쉽게 구현이 가능하다.
    function* myGenerator(){
    	yield	'가나',
      yield	'다라',
      yield	'마바';
    }
    
    for( let t of myGenerator()){
    	console.log(t);
    }

Proxy 객체

  • 객체의 기본 동작을 애플리케이션 독자적인 동작으로 교체하기 위한 객체이다.
    let data={ red:'빨',yellow:'노'};
    var proxy =new Proxy (data,{
    	get(target,prop){
       	return prop in target? target[prop]:'?';
           }
        });
    console.log(proxy.red);//빨
    console.log(proxy.yellow);//노

0개의 댓글