일단 기본 목적이 화면에 표시되는 방법을 제어하는 경우가 더 많기 때문에, 기존 WinForm의 객체들처럼 각각 만들어져있다면 사용하기에 정말 편할 것 같아서 class와 상속 들에 대해서 알아보게 되었다.
먼저, 기본적으로 javascript에서는 class라는 키워드는 존재하지 않는다. function 키워드를 이용해서 객체를 선언 하게 된다.
1. class의 선언
1.
function
Product() {
this
.name =
''
;
this
.price = 0;
this
.SetValues =
function
(name, price) {
this
.name = name;
this
.price = price; };
this
.ShowName =
function
(id) {
this
.ShowAlert(); $(
'#'
+ id).html(
'Product'
+
this
.name); };
this
.ShowAlert =
function
() { console.debug(
'this is product message '
+
this
.name); };}
class의 선언은 매우 단순한것이. 일반적인 함수의 형태를 취하면서 만들어지게 된다. prototype을 선언해서 만드는 법도 가능하지만, 코드의 가독성이 이게 더 편한 것 같아서. 이 방법을 주로 사용하는 것이 더 나아보인다.
private method나 private property의 경우에는 var 키워드를 이용해서 만들어주고, public의 경우 this 키워드를 이용해서 선언할 수 있다.
2. class의 상속
1.
function
KrProduct() { Product.call(
this
);
this
.ShowAlert =
function
() { console.debug(
'this is krProduct message '
+
this
.name); };}
call method를 이용해서 class를 상속한다.
override 를 하고 싶은 경우, 기존의 method를 동일하게 재 선언해주면 된다.
주의점은 javascript의 객체를 만들때는 protected가 없다는 것이다. 상속된 객체에서 절대로 private method나 property는 사용하지 못한다. 이를 고려해서 만들어줘야지 된다. (객체의 캡슐화에는 매우 불리한 것 같다.)
3. 실행 결과.
1.
$(
function
() { $(
'#testButton'
).click(
function
() {
var
product =
new
Product();
var
product2 =
new
KrProduct();
var
product3 =
new
KrProduct(); product.SetValues(
"Product Name"
, 0); product2.SetValues(
"Product2 Name"
, 1); product3.SetValues(
"Product3 Name"
, 2); product.ShowName(
'testDisplay'
); product2.ShowName(
'testDisplay2'
); product3.ShowName(
'testDisplay3'
); });})
override 시킨 method가 차례대로 실행되는 것을 알 수 있다.