RSS구독하기:SUBSCRIBE TO RSS FEED
즐겨찾기추가:ADD FAVORITE
글쓰기:POST
관리자:ADMINISTRATOR

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

2007/12/04 13:25 2007/12/04 13:25
이 글에는 트랙백을 보낼 수 없습니다
웅쓰:웅자의 상상플러스
웅자의 상상플러스
전체 (379)
게임 (5)
영화 (2)
기타 (23)
맛집 (5)
영어 (2)
대수학 (3)
형태소 (5)
Hacking (9)
Linux (112)
HTML (48)
Application_developing (48)
Web_developing (102)
Window (11)
«   2024/04   »
  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        
  1. 2016/01 (1)
  2. 2015/12 (3)
  3. 2015/10 (3)
  4. 2015/03 (2)
  5. 2015/01 (4)