let saram = {
name: '홍길동',
greeting: function() {
return "hello"+this.name;
}
}
// ES5 이전에는 function 키워드를 class 대신 사용
function People(name, age) {
this.name = name;
this.age = age;
// 생성자 내부에 함수를 추가하면 소스코드가 모든 객체에 복제된다
this.showInfo = function() {
document.write("name: " + this.name + " age: " + this.age);
};
}
var kim = new People("홍길동", 24);
kim.showInfo();
var lee = new People("이길동", 22);
lee.showInfo();
var park = new People("박길동", 24);
park.showInfo();
클래스 생성자 내부에 함수를 추가하면 소스코드가 모든 객체가 복제되는 문제가 있다.
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.showInfo = function() {
document.write("name: " + this.name + " age: " + this.age);
};
var kim = new People("홍길동", 24);
kim.showInfo();
var lee = new People("이길동", 22);
lee.showInfo();
var park = new People("박길동", 24);
park.showInfo();
클래스.prototype은 모든 객체가 공유하는 속성으로 해당 소스코드가 객체 생성에 따라 복제 되지 않고 모든 객체들이 사용가능하다.
const saram = new Saram("홍길동", 24);
class Saram {
constructor(name, age){
this.name = name;
this.age = age;
}
// 메소드 생성 가능
}
let saram = new Saram("홍길동", 24);
window['name'] == window.name == this.name
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(function(num) {
return "<h2>"+num+"</h2>";
});
newArr.forEach(function(elem) {
document.getElementById("demo").innerHTML += elem;
});
1) 기본 문법 : (매개변수) => { 실행 처리 문장 }
2) 매개변수가 없는 경우 : () => { 실행 처리 문장 }
3) 매개변수가 한 개인 경우 괄호 생략 가능
매개변수 => { 실행 처리 문장 }
4) 실행 처리문이 return 한 줄뿐이라면 중괄호 생략 가능
(매개변수, 매개변수) => 반환 값(또는 식)
ex) (a,b) => a+b
5) 객체를 반환 할 때는 괄호가 필요
(매개변수, 매개변수) => (객체)
Box를 드래그하면 Box의 위치가 마우스의 위치에 따라 바뀐다. Target Box 밖의 범위에서 마우스 다운 시 다시 Box의 위치는 원점으로 돌아가고 Target Box 범위 안에서 마우스 다운을 하면 그 위치에 Box가 놓아진다.
mousemove, mouseup, mousedown 이벤트와 콜백함수를 사용하였다.
문자가 새로고침때 마다 재배치되며 3초 뒤에 글자가 사라지도록까지 구현되었다.
class Cell {
constructor(parentElement, content, callback) {
this.callback = callback;
this.parentElement = parentElement;
this.newDiv = document.createElement("div");
this.newDiv.innerHTML = content;
this.newDiv.className = "cell";
parentElement.appendChild(this.newDiv);
return this;
}
startCellEvent() {
this.newDiv.addEventListener('click', (event)=>{
this.callback();
});
}
}
셀 하나에 대한 클래스이다. 생성자에서 newDiv가 셀 하나에 대한 div를 만들고 글을 넣는다. 그리고 이 div 클래스 이름을 cell이라고 정한다. startCellEvent() 메소드로 셀이 클릭되도록 한다.
class Puzzle {
constructor(element) {
this.element = element;
this.cells = []
for(var i=0; i<16; i++) {
this.cells.push(new Cell(this.element, String.fromCharCode(65+i%8), function() {
this.newDiv.innerText = this.newDiv.ch;
}) );
}
}
// shuffle() 메소드
// hide() 메소드
start() {
// 버튼의 이벤트 핸들러 작동
for(var i=0; i<this.cells.length; i++) {
this.cells[i].startCellEvent();
}
return this;
}
}
var puzzle = document.getElementById("puzzle");
new Puzzle(puzzle).shuffle().hide().start();
Puzzle 클래스는 전체 셀들을 담고 있는 div 기능을 담당한다.
생성자에서 Cell 클래스 객체를 생성하고 이를 this.cells에 push한다.
hide() {
setTimeout(()=>{
for(var i=0; i<this.cells.length; i++) {
var ch = this.cells[i].newDiv.innerHTML;
this.cells[i].newDiv.ch = ch;
this.cells[i].newDiv.innerHTML = "";
}
}, 3000);
return this;
}
3초간 셀의 내용을 보여주고 그 후 셀의 내용을 숨기는 메소드이다.
setTimeout의 첫 번째 인자에는 실행할 코드가 들어가고, 두 번째 인자로는 지연시간을 넣는다.
shuffle() {
// cells의 위치를 랜덤하게 0~15까지 내용 뽑아서 섞어준다.
for(var i=0; i<30; i++) {
var j = Math.floor(Math.random() * 16);
var k = Math.floor(Math.random() * 16);
var a = this.cells[j].newDiv;
var b = this.cells[k].newDiv;
var tmp = a.innerText;
a.innerText = b.innerText;
b.innerText = tmp;
}
return this; // 메소드 체인
}
셀의 내용(A, B, C, ...)을 랜덤한 위치에 나타내는 메소드이다. 셀의 위치를 바꾸는 것이 아닌 셀의 내용을 랜덤한 위치로 바꾸어준다.