javascript 객체지향 연습 - LinkedList 만들기 Javascript & HTML & CSS/pure javascript2016. 12. 5. 01:31
javascript를 보다 객체지향적으로 사용하기 위한 연습이 필요하다 생각했다.
대충 다음과 같은 개념들을 넣어 insert까지만 구현해 본 소스다.
- 생성자
- setter, getter : 생성자 내부의 var와 this를 이용
- prototype
- 코드(조만간 delete도 추가할 예정) -
<html>
<head>
<script>
function Node(){
var num = 0;
var next = null;
this.getNum = function(){
return num;
}
this.getNext = function(){
return next;
}
this.setNum = function(_num){
num = _num;
}
this.setNext = function(_next){
next = _next;
}
}
function List(){
var head = null;
this.getHead = function(){
return head;
}
this.setHead = function(node){
head = node;
}
}
List.prototype.insert = function(num){
var newNode = new Node();
newNode.setNum(num);
if(this.getHead() === null){
this.setHead(newNode);
return;
}
var walk = this.getHead();
while(walk.getNext() !== null){
walk = walk.getNext();
}
walk.setNext(newNode);
};
List.prototype.display = function(){
if(this.getHead() === null){
console.log('List is empty');
return;
}
var walk = this.getHead();
while(walk !== null){
console.log('item : ' + walk.getNum());
if(walk.getNext() === null){
break;
}
walk = walk.getNext();
}
};
window.onload = function(){
var list = new List();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);
list.display();
};
</script>
</head>
<body>
</body>
</html>
'Javascript & HTML & CSS > pure javascript' 카테고리의 다른 글
javascript의 유효 범위 (0) | 2016.12.14 |
---|---|
javascript event 전달 막기 (0) | 2016.12.06 |
javascript 객체의 형태 (0) | 2016.12.04 |
javascript 클로저 (0) | 2016.12.04 |
javascript 함수는 parameter로 함수를 전달할 수 있음. (0) | 2016.12.04 |