사용자 도구

사이트 도구


javascript:기초

문서의 이전 판입니다!


Javascript 기초

객체지향 프로그래밍

클래스 만들기

원칙적으로 말해서 JS에는 class는 존재하지 않는다. 단지, 생성자 함수만 존재할 뿐이다.

아래는 Pet 이라는 클래스를 생성한다.

function Pet(name) {
    this.name = name; // name 필드 생성
}
 
Pet.prototype.age = 0; // age 필드 생성
 
// toString 메소드 생성
Pet.prototype.toString = function() {
    return "Pet name : " + this.name + ", age : " + this.age;
}
 
var mong = new Pet("mong"); // 객체 생성
mong.age = 6;
alert(mong);

상속

상속할 때 중요한 부분은 Dog.prototype = new Pet()Dog.prototype.constructor = Dog 부분이다.

// 위에서 이어서, Pet을 상속하는 Dog 생성
function Dog(name, age, breed) {
    Pet.call(this, name);
    this.age = age;
    this.breed = breed;
}
 
// Dog.prototype이 Pet.prototype으로부터 상속하도록 한다.
Dog.prototype = new Pet();
 
// Pet 함수를 가리키는 생성자를 Dog 함수를 가리키도록 변경한다.
Dog.prototype.constructor = Dog;
 
// toString() 메소드 오버라이드
Dog.prototype.toString = function() {
    // 필요할 경우 부모클래스 메소드도 호출 가능
    return "Dog " + Pet.prototype.toString.call(this) + ", breed : " + this.breed;
}
 
var miro = new Dog("Miro", 7, "Pomeranian");
alert(miro);
 
alert("Is miro a Dog? " + (miro instanceof Dog));
alert("Is miro a Pet? " + (miro instanceof Pet));
alert("Is miro an Object? " + (miro instanceof Object));
javascript/기초.1317959376.txt.gz · 마지막으로 수정됨: 2011/10/07 12:49 저자 kwon37xi