상세한 내용은 네이버의 강좌를 보면 좋을 것 같고, 아래와 같이 코드를 기반으로 이해를 해보자.
자바스크립트에서 객체지향을 구현하기 위해서 필요한 것이 프로토타입이다.
자바스크립트에서 객체지향을 구현하기 위해서 사용하는 것은 함수다.
// Dog 객체 생성
var Dog = function() {};
// Dog 프로토 타입선언
Dog.prototype.bow = function() {
alert('bow');
};
Dog.prototype.sit = function() {
alert('sit');
};
// Cat 객체 생성
var Cat = function() {};
// Cat 프로토타입 선언
Cat.prototype = {
sit: function() {
alert('sit');
},
stand: function() {
alert('stand');
}
};
// Dog 객체 생성
var dog = new Dog();
dog.bow();
dog.sit();
// Cat 객체 생성
var cat = new Cat();
cat.sit();
cat.stand();
이상과 같이 객체를 선언하고 프로토타입을 사용하여 함수를 생성하는 방법을 알아 보았다.
// Dog 객체 생성 var Dog = function() {}; // Dog 프로토 타입선언 Dog.prototype.bow = function() { alert('bow'); }; Dog.prototype.sit = function() { alert('sit'); }; // 생성자 함수 일치 시키기 Dog.prototype.constructor = Dog; // Cat 객체 생성 var Cat = function() {}; // Cat 프로토타입 선언 Cat.prototype = { sit: function() { alert('sit'); }, stand: function() { alert('stand'); } }; //생성자 함수 일치 시키기 Cat.prototype.constructor = Cat; var Maltiz = function() {}; Maltiz.prototype = new Dog(); // bow 함수의 overrride Maltiz.prototype.bow = function() { alert('maltiz bow'); }; //생성자 함수 일치 시키기 Maltiz.prototype.constructor = Maltiz; var maltiz = new Maltiz(); maltiz.bow(); maltiz.sit();
위와 같이 Maltiz의 프로토타입을 Dog 로 선언하고, Maltiz의 bow 함수를 오버라이딩해서 재구성할 수 있다.
이렇게 자바스크립트의 function 을 이용하여 객체 지향을 구현할 수 있다.
'프로그래밍 언어 > js' 카테고리의 다른 글
| jQuery 2.0 릴리스 (0) | 2013.04.19 |
|---|---|
| GET 방식으로 호출시 '&', '+' 기호 전달하기 (0) | 2013.04.18 |
| jQgrid의 지정한 칼럼, 지정한 열을 다른색으로 지정하기 (0) | 2013.04.12 |
| Javascript의 Array 의 concat, $.extend 메소드 알아보기 (0) | 2013.04.10 |
| 80020101 오류 해결하기 (0) | 2013.02.15 |