Object객체
속성과 동작의 집합체로 이루어진 것을 객체라고 한다.
1) 객체를 만드는 방법 1
const person = {};
person.name = '툰도리';
person.age = 12;
person.introduce = function() {
console.log('안녕하세요? 저는 툰도리이고 나이는 12살이에요.');
};
// 객체의 값으로도 대입이 가능하다.
person.introduce();
2) 객체를 만드는 방법 2
const person = {
name: '툰도리',
age: 12,
introduce: function(){
console.log('안녕하세요? 저는 툰도리이고, 나이는 12살이에요.');
}
};
console.log(person.name);
person.introduce();
3) 객체를 만드는 방법 3
const person = {
name: '툰도리',
age: 12,
introduce: function(){
consolelog('안녕하세요? 저는' + this.name + '이고, 나이는' + this.age + '살이에요.');
};
this : this를 사용하면 객체가 메서드를 실행했을 때 가리키는 주체객체이다. 메서드를 실행한 주체객체를 가리킨다. this를 붙이면 객체의 속성값에 접근이 가능하다. 이벤트 핸들러에서 객체는 addEventHander로 발전시킨다.
name이 에러가 나지 않은 이유, 윈도우 전역객체의 name속성을 보면 빈 문자열이 보인다. 스크립트의 바깥영역에 있는 것이다. window 전역객체가 갖고 있기 때문에 에러가 나지 않는다.
4) 객체를 만드는 방법 4 : 템플릿 문자열
const name = '일분이';
const age = 10;
console.log(안녕하세요? 저는 ${name}이고, ${age}살이에요.);
백틱과 ${}를 사용해서 만들어도 된다. 덧셈도 가능하고, 변수도 가능한 표현식이다.
기존 사용하던 방법
const elemHtml = ''
+ '
장점
복잡한 html 을 간단하게 표현할 수 있다.
Internet Explorer에서는 사용이 어려운 표현식이다.
const elemHtml1 = `
<div class="character">
캐릭터
</div>
`;
document.body.innerHTML = elemHTML2;
이런식으로 작성이 가능하다.
5) 생성자로 인스턴스를 만들기
function Card(num, color) {
this.num = num;
this.color = color;
this.init();
}
Card.prototype = {
// prototype의 생성자를 card로 따로 setting을 해야한다. this의 init메서드를 생성한다.
constructor: Card,
init: function() {
const mainElem = document.createElement('div');
mainElem.style.color = this.color;
mainElem.innerHTML = this.num;
mainElem.classList.add('card');
document.body.appendChild(mainElem);
}
};
const card1 = new Card(1, 'green');
const card2 = new Card(7, 'blue');
}}