JavaScript OOP, Prototype)

1. 객체에 속성이용

man.name="홍길동";

Man["name"] = "홍길동";

 

 

 

2. 함수 추가

1) 익명의 함수 이용

(함수의 이름이 없고 몸체만있는 함수) 

Man.getName = fuction(){

       return this.name;

}

 

 

 

 

 

2) 객체 외부 함수 이용

function printName()

{

       alert(this.name);

}

Man.getName = printName; // 괄호를 사용하지 않음

 

 

 

3. 객체 생성

 

1) new Object(); 방식

 new Object();

 var man = new Object();

 man.name = "홍길동";

 

 

2) 생성자이용

function ManObject(name, height){

       this.name = name;

       this.height = height;

}

Var man = new ManObject("홍길동", 170);

Alert(man.name + " / " + man.height);

 

3) 생성자를 이용한 방식에서 클래스에 메소드 추가

function ManObject(name, height){

 this.name = name;

 this.height = height;

 

this.getName = function(){

       return this.name

} // 생성자에 직접 함수 정의

}

 

Prototype 속성은 모든 자바스크립트 객체의 기본속성이다.

--어떤 객체의 prototype 속성이나 함수를 정의 한다는 것은 앞으로 객체에 공통적으로 적용되는 속성이나 함수를 정의한다는 의미

 

 

 

 

4.Prototype 이용

function ManObject(name, height){

       this.name = name;

       this.height = height;      

} // 생성자를 만들고 함수는 생성자 안에 지정하지 않음

 

ManObject.prototype.getName = function(){

       return this.name;

} // prototype 속성에 새로운 함수를 붙임

 

 

생성자에 함수 정의

인스턴스를 여러 만들때 인스턴스는 메모리로 상주. 인스턴스마다 함수와 같이 생김

Prototype 이용

함수가 단한번 만들어지고 모든 인스턴스는 프로로타입 함수를 공유한다.

객체안에 내장된 함수가 객체의 지역변수를 자신의 지역변수처럼 사용할 경우 이러한 함수를 클로저라 한다.

 

 

 

 

5.클로저

1-1) 클로저 발생 하는 경우

function MyObject(){

       var startTime = new Date();

       this.elapsedTime = function(){

              var now = new Date();

              var elapsed = now - startTime;

              return elapsed;

       }

}      // 클로저 : startTime 함수 안에 없고, 클래스 변수         //startTime 참조함

       //클로저발생 => 함수 안에서 사용하는 외부의 지역변수는

       //깨긋이 지워지지 않고 함수에 묶여있어 메모리 누수현상발생.

  

 

 

 

 

1-2) 참조할수 있는 startTime이 없어 오류발생 하는 경우

function MyObject(){

       var startTime = new Date();

       this.elapsedTime = getElapsed;

}

function getElapsed(){

     var now = new Date();

     var elapsed = now + startTime();        return elapsed;

}

 

 

 

1-3) 클로저 발생안되게 사용하는 방법

function MyObject(){

       this.startTime = new Date();

}

MyObject.prototype.elapsedTime = function(){

      var now = new Date();

      var elapsed = now + this.startTime;      

      return elapsed;

}

 

 

 

 

 

 

6.Prototype 성질 

 

1) Prototype 속성 변경  

이전에 만들 객체의 속성은 자동으로 변경

 프로토 타입 영역의 속성은 모든 인스턴스간에 공유

function MyObject(){ }

 

MyObject.prototype.color = "blue";

var obj1 = new MyObject();

alert(obj1.color); // blue

MyObject.prototype.color = "red";

car obj2 = new MyObject();

alert(obj1.color + " / " + obj2.color); // red / red

 

 

 

 

2) Prototype 이용한 내장객체 확장

Object.prototype.log = function(){

document.write("this:" + this);

//최상위 객체인 Object 프로토타입에 log함수 추가 => 모든 자바스크립트 객체, 변수에 대해서 log메소드 사용가능

}

var arr = new Array(0,1,2);

arr.log(); // this : 0, 1, 2

var name = "mike";

name.log(); // this : mike

var sum = 1 + 3;

sum.log();       //this : 4

 

 

 

 

 

 

7. 자바스크립트 객체의 상속

1-1) 상속 - prototype 을 이용한 부모 클래스 지정방법 (부모클래스 생성자 매개변수 없는경우)

function ManObject(){ }

       ManObject.prototype.eyeCnt = 2;

       ManObject.prototype.getEyeCnt = function(){

              return this.eyeCnt;

}

function AsianMan(){

       this.eyeColor = "black";

}

AsianMan.prototype = new ManObject();//AsianMan 부모클래스는 ManObject

 

 

function WesternMan(){

       this.eyeColor = "blue";

}

WesternMan.prototype = new ManObject();//WesternMan 부모클래스는 ManObject

 

 

var HongGilDong = new AsianMan();

var smith = new WesternMan();

 

alert(HongGilDong.eyeCnt); // 2

alert(HongGilDong.eyeColor); // black

alert(HongGilDong.getEyeCnt()); // 2

alert(smith.eyeCnt); //2

alert(smith.eyeColor); // blue

alert(smith.getEyeCnt()); // 2

 

 

 

 

 

 

 

1-2) 상속 - prototype 을 이용한 부모 클래스 지정방법 (부모클래스 생성자 매개변수 있는경우)

/**

 * 사람 클래스

 * @param {String} name

 * @param {String} age

 */

function Person(name){

       this.name = name;

 

       this.getName = function(){

              return this.name;

       }

}

 

var gradeEnum = {

       one        : 1 ,

       two        : 2,

       tree       : 3

}

 

function Student(name, schoolName){      

       this.schoolName = schoolName;      

       this.getSchoolName = function (){

              return this.schoolName;

       }      

             

       this.grade;

       this.getGrade = function(){

              return this.grade;

       }      

}

Student.prototype = new Person("홍길동"); //순서가 중요.제일 먼저Student.prototype을 지정해야함.

 

/**

 * prototype 이용한 setGrade 메소드 확장

 * @param {gradeEnum} grade

 */

Student.prototype.setGrade = function (grade){

       this.grade = grade;

}

var student = new Student("홍길동" ,  "홍길동대학교");

alert(student.getName());                    //홍길동

alert(student.getSchoolName());              //홍길동대학교

student.setGrade(gradeEnum.tree);      

alert(student.getGrade());                   //3

 

 

 

 

 

 

 

2-1) 상속 - base 속성,메소드를 이용한 방법(부모클래스 생성자 매개변수 없는경우)

function ManObject(){

       this.eyeCnt = 2;

       this.getEyeCnt = function(){

              return this.eyeCnt;

       }

}

 

 

// AsianMan 부모클래스는 ManObject;

function AsianMan(){

       this.base = ManObject;

       this.base();

       this.eyeColor = "black";

}

 

 

 

 

 2-2) 상속 - base 속성,메소드를 이용한 방법(부모클래스 생성자 매개변수 있는경우) 

/**

 * 사람 클래스

 * @param {String} name

 * @param {String} age

 */

function Person(name){

       this.name = name;

 

       this.getName = function(){

              return this.name;

       }

} 

 

var gradeEnum = {

       one        : 1 ,

       two        : 2,

       tree       : 3

} 

function Student(name, schoolName){      

       this.base = Person;             //부모클래스 지정

       this.base(name);                //부모클래스 생성자호출

 

       this.schoolName = schoolName;      

       this.getSchoolName = function (){

              return this.schoolName;

       }      

             

       this.grade;

       this.getGrade = function(){

              return this.grade;

       }      

}

  

/**

 * prototype 이용한 setGrade 메소드 확장

 * @param {gradeEnum} grade

 */

Student.prototype.setGrade = function (grade){

       this.grade = grade;

}

 

var student = new Student("홍길동" ,  "홍길동대학교");

alert(student.getName());                    //홍길동

alert(student.getSchoolName());              //홍길동대학교

student.setGrade(gradeEnum.tree);      

alert(student.getGrade());                   //3

 

 

 

 

 

 

 

 

9. for 문의 재발견 

for(var param in args){

       alert(param);

}

 

 

 

 

 

 

 

 

마치며)

이로써 간단하게나마 JavaScript OOP와 더불어 prototype속성에 대해서도 알아보았습니다.

아참, prototype.js 라는 JavaScript 프레임워크 추천합니다.

하지만 코드의 가독성이 떨어진다, 맘에 안든다 하시는분은 prototype.js 에서 지원하는

Ajax쪽만 활용하셔도 괜찮을듯 싶네요..

 

아울러 JavaScript로 XML관련 핸들링하는것도 제 블로그에 있으니 참고하시구요.

(http://blog.naver.com/jadin1/70008395017)

 

[출처] [DEV.WON] JavaScript - OOP 와 prototype|작성자 데브원

'IT' 카테고리의 다른 글

Google Sync  (0) 2009.05.20
Telnet 으로 port 확인  (2) 2009.03.18
Prototype Javascript Framework  (0) 2009.02.16
VS 단축키  (0) 2009.02.09
현재 컴퓨터에 설치된 디바이스 장치 정보 알아오기  (0) 2009.02.09

+ Recent posts