다음의 식은 객체를 만드는 class임을 기억하자!
let Node = function (value) {
this.value = value;
this.children = [];
};
클래스로 객체를 생성하는 방법은 다음과 같다
let root = new Node(1);
root = {
value: 1
children: []
}
클래스에 메소드를 만들어 주는 방법은 다음과 같다
Node.prototype.addChild = function (child) {
this.children.push(child);
return child;
};
노드를 만들어보자!
let root = new Node(1);
let rootChild1 = root.addChild(new Node(2));
let rootChild2 = root.addChild(new Node(3));
let leaf1 = rootChild1.addChild(new Node(4));
let leaf2 = rootChild1.addChild(new Node(5));
console.log(root);
결과
Node = {value: 1,
children: [{value: 2,
children: [{value: 4, children: []},
{value: 5, children: []}
]
},
{value: 3,
children: []
}
]
}