Ext JS - Learning Center

Manual:Intro:Class Design kr

From Learn About the Ext JavaScript Library

Revision as of 19:03, 16 April 2008 by Falko (Talk | contribs)
(diff) ← Older revision | Current revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Summary: Class Design
Author: Maxence Delannoy (번역:Teo Lee)
Published: July 29, 2007
Ext Version: 1.1
Languages: en.png English cn.png Chinese fr.png French

kr.png Korean ru.png Русский

Javascript는 C++, Java, PHP와 같은 다른 객체 지향 언어와는 다르다. Javascript는 클래스(class) 컨셉에 기반하지 않고 프로토타입(prototype)이라 불리우는 컨셉을 사용한다.

객체생성(Object creation)

Javascript에서 객체를 만드는 것은 매우 간단하다 :

var myObject = {
  aVar: 15,
  aMethod: function() {
    alert("I'm a method of the object myObject." + "aVar: " + this.aVar);
  }
}

객체를 생성하기 위해 클래스를 정의하고 이를 초기화할 필요가 없다. 자바스크립트에서는 객체 초기화 연산자(object initializer)를 사용한다. 이는 단일 객체인 경우에 완벽하다. 동일한 형태를 가지는 복수 객체가 필요하다면 생성자 함수와 new 키워드를 사용해야 한다.

생성자 함수 사용(Using a Constructor Function)

Javascript에서는 생성자(constructor)는 존재하지만 클래스(class)는 존재하지 않는다. 생성자 함수를 기술하고 new 키워드로 객체를 생성한다.

// At first, we write an empty constructor for our class
function myClass() {
  this.aVar = 15;
  this.aMethod = function() {
    alert("I'm a method of the object myObject.");
  }
}
 
// We make an instance of our class
var A = new myClass();
 
// Display 15
alert(A.aVar);
 
// 2nd instance
var B = new myClass();

메서드 공유(Share methods)

클래스의 모든 인스턴스(instance)는 단일 프로토타입(prototype) 객체를 공유한다. 함수와 공유되는 값이 여기에 기술된다.

// We define a method of the prototype object
Ext.apply(myClass.prototype, {
 
    defaultClassName: "x-widget-class",
 
    sharedMethod: function() { alert("I'm a shared method") }
});
 
//  Display our message
A.sharedMethod();
 
// Same message
B.sharedMethod();

myClass의 정의에서 sharedMethod로 명명된 함수는 없다. Javascript는 myClass의 프로토타입 객체에서 이 이름을 가진 메서드를 찾고 만약 존재한다면 그 함수를 호출한다.